【问题标题】:Binary tree traversal Inorder output is wrong why?二叉树遍历中序输出错误为什么?
【发布时间】:2020-12-26 04:42:25
【问题描述】:

谁能解释为什么我的输出是错误的以及如何解决它?

例如:我将输入 A B C D E

输出给我 A B C D E

Insead 中序遍历: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);
}
}  

我仔细检查了遍历顺序的算法,但我的输出仍然是错误的,我不明白为什么?我错过了什么吗

【问题讨论】:

    标签: linked-list tree inorder


    【解决方案1】:

    结果符合预期。中序遍历不应为您的 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
    

    这是正确的。

    【讨论】:

      猜你喜欢
      • 2021-07-07
      • 2021-09-17
      • 2021-03-08
      • 2020-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-01
      相关资源
      最近更新 更多