c语言 数组实现二叉树

Modified on: Thu, 21 Mar 2019 22:23:00 +0800 热度: 1,703 度
#include <stdio.h>
#include <stdlib.h>
typedef struct{
    int *pTree;
    int size;
}tree;
void Tree(tree *t,int *pRoot,int size);
void Distroy(tree *t);
int * SearchNode(tree *t,int nodeIndex);
int  AddNode(tree *t,int nodeIndex,int direction,int *pNode);
int  DeleteNode(tree *t,int nodeIndex,int *pNode);
void TreeTraverse(tree *t);

void Tree(tree *t,int *pRoot,int size)
{
    int i;
    t->pTree=(int *)malloc(size*sizeof(int));
    t->size=size;
    for(i=0;i<size;i++)
    {
        t->pTree[i]=0;
    }
    t->pTree[0]=*pRoot;
}
void Distroy(tree *t)
{
    free(t->pTree);
    t->pTree=NULL;
}
int * SearchNode(tree *t,int nodeIndex)
{
    if(nodeIndex<0||nodeIndex>=t->size)
    {
        return NULL;
    }
    if(t->pTree[nodeIndex]==0)
    {
        return NULL;
    }
    return &t->pTree[nodeIndex];
}
int  AddNode(tree *t,int nodeIndex,int direction,int *pNode)
{
    if(nodeIndex<0||nodeIndex>=t->size)
    {
        return -1;
    }
    if(t->pTree[nodeIndex]==0)
    {
        return -1;
    }
    if (direction==0)
    {
        if(nodeIndex*2+1>=t->size)
        {
            return -1;
        }
        if(t->pTree[nodeIndex*2+1]!=0)
        {
            return -1;
        }
        t->pTree[nodeIndex*2+1]= *pNode;
    }
    if (direction==1)
    {
        if(nodeIndex*2+2>=t->size)
        {
            return -1;
        }
        if(t->pTree[nodeIndex*2+2]!=0)
        {
            return -1;
        }
        t->pTree[nodeIndex*2+2]= *pNode;
    }
    return 0;
}

int  DeleteNode(tree *t,int nodeIndex,int *pNode)
{
    if(nodeIndex<0||nodeIndex>=t->size)
    {
        return -1;
    }
    if(t->pTree[nodeIndex]==0)
    {
        return -1;
    }
    *pNode=t->pTree[nodeIndex];
    t->pTree[nodeIndex]=0;
    return 0;
}
void TreeTraverse(tree *t)
{
    int i;
    for(i=0;i<t->size;i++)
    {
        printf("%d ",t->pTree[i]);
    }
    putchar(10);
}

添加新评论