【问题标题】:Given a binary tree, traverse the left sub tree给定一棵二叉树,遍历左子树
【发布时间】:2015-02-24 13:47:42
【问题描述】:

如果我们要在左子树甚至根节点上查找节点,它会给出正确的输出,但是如果我们在右边取任何节点说 root->right 即节点 70,它会给出错误的输出 20 30 40 50 60。我知道我在哪里犯了错误我应该如何修改代码,以便对于 70 的输入只有左子树,即打印节点 60。

void In(struct node *root1,struct node*root2) 
{
  if (root1 != NULL)
  {
    In(root1->left,root2);
     if(root1->key==root2->key)
       exit(0);
     else
       printf("%d ", root1->key);
    In(root1->right,root2);
   }
}
int main()
{
  /* Let us create following BST
          50
       /     \
      30      70
     /  \    /  \
   20   40  60   80 */
  struct node *root = NULL;
  root = insert(root, 50);
    insert(root, 30);
    insert(root, 20);
    insert(root, 40);
    insert(root, 70);
    insert(root, 60);
    insert(root, 80);

  // print inoder traversal of the BST
   inorder(root);
   printf("\n");
   In(root,root->right);
   return 0;
}

【问题讨论】:

  • 您需要更好地表达您的问题。解释In() 的两个参数是什么。
  • @KacyRaye 代码在 main 函数的第二个参数中的节点 70 的输入上给出了不正确的输出,即如果要找到节点 70 的左子树
  • 所以你要打印出两个参数的左子树?
  • 不,第一个参数是根节点,第二个参数是我们想要的 lst 的节点。我正在遍历树,这样如果当前节点与我们需要找到它的第一个节点匹配,它就会退出并且不再打印。取一个值说 50 你会理解实现

标签: binary-tree


【解决方案1】:

只需对左孩子进行有序遍历即可。

void In( struct node *root1, struct node *root2 ) 
{
    if ( root1 != NULL && root2 != NULL )
    {
        if ( root1 -> key == root2 -> key)
            exit(0);

        inorder( root2 -> left );  
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-02
    • 2011-04-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多