Write an algorithm to find the 'next' node(i.e. in-order successor) of a given node in a binary search tree.
这道题让我们寻找给定节点的中序后继节点,最简单的方法就是中序遍历tree, 并用一个prev指向当前的节点的前面的节点,如果prev等于等于给定节点,当前节点就是所求。见如下代码:
def inorder_successor(root, node) $prev = nil $succ = nil inorder(root, node) $succ end def inorder(root, p) return if root.nil? inorder(root.left, p) if $prev == p $succ = root end $prev = root inorder(root.right, p) end