我们必须逐级地在二进制树中插入元素,即为数组:
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);
}
最佳答案
您正在按值传递tree
; insert
返回后,调用NULL
的任何人仍然具有insert
指针。有关某些背景,请参见What's the difference between passing by reference vs. passing by value?。
关于c++ - 在二叉树中插入级别顺序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13170036/