二叉树中的级别顺序插入

时间:2012-11-01 02:12:32

标签: c++ tree binary-tree insertion

我们必须逐级地在二叉树中插入元素,即对于数组:

a = {1,2,3,4,5,6}

1st level = [1]
2nd level = [2, 3]
3rd level = [4, 5, 6]

我已经编写了一个代码,但每次都会产生NULL树。

struct node
{
    int data;
    struct node* left;
    struct node* right;
};

node* create(int x)
{
    node* tmp;
    tmp=(struct node *)malloc(sizeof(struct node));
    tmp->data=x;
    tmp->left=NULL;
    tmp->right=NULL;
    return tmp;
}

struct node* tree;

void insert(struct node* tree, int* a, int start, int n)
{
    int left =2*start+1;
    int right=2*start+2;
    if(left>n || right>n)
        return;
    if(tree==NULL)
    {
        tree=create(a[start]);
    }
    if(tree->left==NULL && tree->right==NULL)
    {
        if(left<n)
            tree->left=create(a[left]);
        if(right<n)
            tree->right=create(a[right]);
    }
    insert(tree->left,a,left,n);
    insert(tree->right,a,right,n);
}

1 个答案:

答案 0 :(得分:1)

您按值传递tree;在insert返回后,任何调用NULL的人仍然有一个insert指针。有关背景信息,请参阅What's the difference between passing by reference vs. passing by value?