问题描述
有人可以解释为什么我的输出是错误的以及如何修复它吗?
例如:我将输入 A B C D E
输出给了我 A B C D E
insead of Inorder Traversal: D B E A C
这是我的代码:
int main()
{
struct node *root = NULL;
int choice,n; // item
char item;
do
{
printf("\n1. Insert Node");
printf("\n2. Traverse in Inorder");
printf("\nEnter Choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
root = NULL;
printf("\n\n Nodes : ");
scanf("%d",&n);
for(int i = 1; i <= n; i++)
{
printf("\nEnter data for node %d : ",i);
scanf(" %c",&item);
root = Create(root,item);
}
break;
case 2:
printf("\nBST Traversal in INORDER \n");
Inorder(root); break;
default:
printf("\n\nINVALID OPTION TRY AGAIN\n\n"); break;
}
} while(choice != 3);
}
struct node *Create(struct node *root,char item)
{
if(root == NULL)
{
root = (struct node *)malloc(sizeof(struct node));
root->left = root->right = NULL;
root->data = item;
return root;
}
else
{
if(item < root->data )
root->left = Create(root->left,item);
else if(item > root->data )
root->right = Create(root->right,item);
else
printf(" Duplicate Element !! Not Allowed !!!");
return(root);
}
}
void Inorder(struct node *root)
{
if( root != NULL)
{
Inorder(root->left);
printf(" %c ",root->data);
Inorder(root->right);
}
}
我仔细检查了遍历中序的算法,但我的输出仍然是错误的,我不明白为什么?我在这里错过了什么
解决方法
结果如预期。中序遍历不应为 A B C D E 的输入产生 D B E A C
这就是树的构造方式。
首先使用值 A 创建根
然后插入B。作为 B > A,它作为根的右孩子插入:
A
\
B
然后插入B。当 C > A 时,它被插入到右子树中。我们再次发现 C > B,因此新节点将作为 B 的右孩子插入:
A
\
B
\
C
以同样的方式插入 D 和 E,得到这棵树:
A
\
B
\
C
\
D
\
E
请注意,这棵树根本不平衡。当您按词汇顺序插入节点时,就会发生这种情况。如果您以更随机的顺序插入它们,我们希望树更平衡。
但是对于中序遍历实际上并不重要。你实现的是一个二叉搜索树(BST)。 BST 的一个重要特性是它们的有序遍历总是以正确的顺序生成数据。所以不管你输入字母 A B C D 和 E 的顺序如何,有序遍历应该总是输出这个序列:
A B C D E
这是正确的。