【问题标题】:inorder traversal in BSTBST中的中序遍历
【发布时间】:2012-03-08 07:02:31
【问题描述】:

如何在递归中序二叉搜索树遍历中跟踪前一个节点?

当... 在寻找任何没有的地板......在bst中......我试图找到bst中大于给定值的第一个数字......然后打印上一个节点的数据,该数据等于或小于给定值,因为它是中序遍历...

那么为什么问题是我们如何跟踪 bst 中的前一个节点 递归中序遍历??

【问题讨论】:

  • 为什么你需要在递归中序遍历中跟踪前一个节点?
  • 我的任务是找到楼层...即如果 1,4,7,9,14,16 的顺序比 12 的楼层是 9...所以我找到第一个。这大于给定值,这里是 14...所以回答我们 9,即按顺序排列的前一个节点...所以我想问我们如何跟踪前一个节点...

标签: c algorithm data-structures binary-tree


【解决方案1】:

(旁白:听起来您不是在要求按顺序遍历,而是要求使用二分查找函数,它返回不大于查询的最大节点。)

在递归算法中跟踪此类内容的两种最常见方法是将其作为参数传递或返回给它。 (无论哪种方式,您都在堆栈上存储有关过去的信息。)

在您的情况下,后者可能是最干净的。例如:

Node* floor_node(int x, Node *subtree) {
  if (subtree) {
    if(subtree->value > x) {
      return floor_node(x, subtree->left);
    } else {
      return floor_node(x, subtree->right) || subtree;
    }
  } else {
      return subtree;
  }
}

【讨论】:

    【解决方案2】:

    二叉树递归的工作原理是先从左树向下,然后再向右。 Inorder/preorder/postorder 是一种约定,它仅由递归过程中某些局部动作的排序决定:关于两个递归调用,当前节点本身的“访问”时间。

    如何获得下一个节点是让递归返回它。

    当你递归到树中时,“inorder”中访问的最后一个节点就是最右边的节点!因此,您的递归必须简单地返回最右边的节点。

    另外,如果一棵树T作为一个整体有前一个节点P,那么T的左子树,即left(T)也有相同的前一个节点P。P是T最左边节点的前驱。

    此外,关于right(T)的前一个节点是节点T本身。

    所以当递归到左(T)时,我们可以简单地传递给我们的同一个前任,当递归到右(T)时,我们将自己作为前任传递。

    伪代码:

    # a recursive function that is given its previous node,
    # and returns the rightmost node
    
    recurse_with_previous (tree previous-in):
       # skip empty link. No leaf to see here!
       # previous-in is the rightmost node still
       if null(tree)
          return previous-in
    
       # if we are at a leaf, then that leaf is rightmost
       if leaf(tree)
          print "visiting leaf node " tree " with previous node " previous-in
          return tree
    
       # the previous node (previous-in) of this tree is actually the left
       # subtrees previous node, so we just pass that parameter down
       previous = recurse_with_previous (left(tree) previous-in)
    
       # inorder visit: visit this node between the subtrees
       print "visiting " tree " with previous node " previous
    
       # now the right subtree. what is ITS previous? Why, we are!!!
       # we return whatever this returns causing the return value
       # to be the rightmost node.
       return recurse_with_previous (right(tree) tree)
    
     # how to call
     recurse_with_previous(some-tree nil)
    

    【讨论】:

    • 我喜欢这个网站。发明一种伪代码语言,它会当场获得语法高亮。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-31
    • 1970-01-01
    相关资源
    最近更新 更多