【发布时间】:2017-12-24 06:55:10
【问题描述】:
我为严格的二叉搜索树编写了这段代码。 (如果二叉树中的每个非叶子节点都有非空的左子树和右子树,则该树称为严格二叉树。或者,换句话说,严格二叉树中的所有节点的度数均为 0 或 2 ,从不一阶。具有 N 个叶子的严格二叉树总是包含 2N – 1 个节点。)不幸的是,它不能正确打印值。我不知道有什么问题。我在互联网上看过其他网站,代码几乎相同,但我仍然无法在我的代码中找到错误。
#include <stdio.h>
#include <stdlib.h>
struct node
{
struct node* prev;
int data;
struct node* next;
};
void Binary_Search_Tree(struct node *newnode,struct node *p);
void print(struct node* p);
main()
{
struct node *root,*nnode,*temp;
int c,d;
root=malloc(sizeof(struct node));
printf("Enter the root data\t");
scanf("%d",&d);
root->data=d;
root->prev=NULL;
root->next=NULL;
while(1)
{
printf("Enter your choice\n1 insert element.\n2 print tree.\n3 Exit");
scanf("%d",&c);
switch(c)
{
case 1:
nnode=malloc(sizeof(struct node));
printf("Enter the node data\t");
scanf("%d",&d);
nnode->data=d;
nnode->prev=NULL;
nnode->next=NULL;
temp=root;
Binary_Search_Tree(nnode,temp);
break;
case 2:
temp=root;
print(temp);
break;
case 3:
free(root);
free(nnode);
free(temp);
temp=nnode=root=NULL;
exit(1);
break;
}
}
return 0;
}
void Binary_Search_Tree(struct node *newnode,struct node *p)
{
if(newnode->data<p->data)
{
if(p->prev=NULL)
{
p->prev=newnode;
}
else if(p->prev!=NULL)
{
p=p->prev;
Binary_Search_Tree(newnode,p);
}
}
else if(newnode->data>p->data)
{
if(p->next=NULL)
{
p->next=newnode;
}
else if(p->next!=NULL)
{
p=p->next;
Binary_Search_Tree(newnode,p);
}
}
}
void print(struct node* p)
{
if(p!=NULL)
{
print(p->prev);
printf("%d\n",p->data);
print(p->next);
}
}
【问题讨论】:
-
“正确打印值” - 请指定预期值和实际值
-
您应该展示一些示例输入,以及实际和预期的输出(ir 是创建 MCVE 的重要部分 — minimal reproducible example)。当您一次添加一个节点时,如何确保严格的二叉树尚不清楚。不需要添加 1,然后 2,然后 4,然后 8 个节点吗?
-
好吧,我添加了 2 个字符并解决了问题...
if(p->prev=NULL)-->if(p->prev==NULL)和p->next=NULL-->p->next==NULL -
如果您在二元运算符周围放置空格,那么阅读代码会容易得多。阅读
else if(newnode->data>p->data)而不是else if (newnode->data > p->data)更难;找到标记需要更多的努力,尤其是当箭头和>是按顺序排列的时候。如果你写if(p->next = NULL),它也更容易发现if(p->next=NULL)是错误的;更明显的是应该是if(p->next == NULL)。 -
下一次,使用所有警告和调试信息进行编译:
gcc -Wall -Wextra -g和 GCC。改进代码以获得没有警告。使用调试器gdb
标签: c binary-search-tree