[英]Unexpected Pre-order traversal of Tree
When I am executing my code, I am getting the wrong result for a pre-order traversal of my binary tree. 当我执行我的代码时,对于遍历我的二进制树,我得到了错误的结果。 I am expecting that my program print this pre-order 5 -> 4 -> 3 -> 2-> 6 -> 7 -> 8. I am not able to point out my mistake in code.
我期望我的程序按此顺序打印5-> 4-> 3-> 2-> 6-> 7->8。我无法指出我的代码错误。 Please tell me where I have made a mistake.
请告诉我我哪里做错了。
This is my input and output (a sample run): 这是我的输入和输出(示例运行):
ENTER THE NODE DATA
5
ENTER YOUR CHOICE
ENTER THE NODE DATA
4
ENTER YOUR CHOICE
ENTER THE NODE DATA
6
ENTER YOUR CHOICE
ENTER THE NODE DATA
3
ENTER YOUR CHOICE
ENTER THE NODE DATA
7
ENTER YOUR CHOICE
ENTER THE NODE DATA
2
ENTER YOUR CHOICE
ENTER THE NODE DATA
8
ENTER YOUR CHOICE
5 -> 4 -> 3 -> 2 -> 8 -> 7 -> 6 ->
This is the code for creating the binary tree and printing a pre-order traversal of the tree. 这是用于创建二叉树并打印该树的预遍历的代码。
#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
struct node {
int data;
struct node *right;
struct node *left;
} *tmp = NULL;
typedef struct node NODE;
NODE *root = NULL;
NODE *child, *new_node;
void preorder(NODE *t)
{
if(t != NULL)
{
printf("%d -> ",t->data);
preorder(t->left);
preorder(t->right);
}//IF
}
int main ()
{
char choice;
do{
new_node = (NODE *)malloc(sizeof(NODE));
printf("ENTER THE NODE DATA \n");
scanf("%d",&new_node -> data);
new_node -> right = NULL;
new_node -> left = NULL;
if(root == NULL)
{
root = new_node;
tmp = new_node;
}//IF
else
{
child = new_node;
while(1)
{
if(child -> data < tmp -> data)
{
if(tmp -> left == NULL)
{
tmp -> left = new_node;
break;
}//if2
tmp = tmp -> left;
}//if1
if(child -> data > tmp -> data)
{
if(tmp -> right == NULL)
{
tmp -> right = new_node;
break;
}//if4
tmp = tmp -> right;
}//if3
}//while
}//else
printf("\n ENTER YOUR CHOICE \n");
choice = getch();
}//do
while(choice != 'n');
preorder(root);
getch();
return 0;
}//main
You didn't reset tmp
to be the root in every iteration. 您没有将
tmp
重置为每次迭代的根。
Note that there is no need for variable child
at all, as its value is completely identical to that of new_node
. 请注意,根本不需要变量
child
,因为它的值与new_node
值完全相同。
In do while add the following statement. 在做的同时添加以下语句。
else {
child=new_node;
tmp=root;
...
...
}
After every loop, tmp value will be changed. 在每个循环之后,tmp值将被更改。 We have to check the new value with the root itself.
我们必须用根本身检查新值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.