【发布时间】:2015-06-27 08:32:33
【问题描述】:
我必须将每个级别的二叉搜索树的节点放在一个链表中。也就是说,如果树的高度为“h”,则将创建“h+1”链表,然后每个链表将包含每个级别的所有节点。为此,我想到了创建一个链表数组。但是我猜这些节点没有被插入到列表中。代码如下:-
struct node{
int data;
struct node *left;
struct node *right;
};
struct linked_list
{
int data;
struct linked_list *next;
};
linkedlistofbst(struct node *new,struct linked_list *n1[], int level)
{
//printf("%d ",new->data);
if(new==NULL)
{
return;
}
if(n1[level]==NULL)
{
struct linked_list *a =(struct linked_list *)malloc(sizeof(struct linked_list));
a->data=new->data;
a->next=NULL;
n1[level]=a;
printf("%d ",a->data);
}
else
{
struct linked_list *b =(struct linked_list *)malloc(sizeof(struct linked_list));
while(n1[level]->next!=NULL)
{
n1[level]=n1[level]->next;
}
b->data=new->data;
b->next=NULL;
n1[level]=b;
}
linkedlistofbst(new->left,n1,level+1);
linkedlistofbst(new->right,n1,level+1);
}
main()
{
struct linked_list *l=(struct linked_list *)malloc((a+1)*sizeof(struct linked_list));//'a' is the height of the tree
linkedlistofbst(new,&l, 0);//new is the pointer to the root node of the tree.
}
【问题讨论】:
-
您使用哪种编程语言?
-
我用的是C语言
标签: c arrays linked-list binary-search-tree