我们必须在二叉树中逐级插入元素,也就是说,对于一个数组:
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);
}