In Order Successor in Binary Search Tree

前端 未结 17 1836
孤独总比滥情好
孤独总比滥情好 2020-11-27 04:11

Given a node in a BST, how does one find the next higher key?

17条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-27 04:37

    We can find the successor in O(log n) without using parent pointers (for a balanced tree).

    The idea is very similar to when you have parent pointers.

    We can define a recursive function that achieves this as follows:

    • If the current node is the target, return the left-most / smallest node of its right subtree, if it exists.
    • Recurse left if the target is smaller than the current node, and right if it's greater.
    • If the target is to the left and we haven't found a successor yet, return the current node.

    Pseudo-code:

    Key successor(Node current, Key target):
       if current == null
          return null
       if target == current.key
          if current.right != null
             return leftMost(current.right).key
          else
             return specialKey
       else
          if target < current.key
             s = successor(current.left, target)
             if s == specialKey
                return current.key
             else
                return s
          else
             return successor(current.right, target)
    
    Node leftMost(Node current):
        while current.left != null
           current = current.left
        return current
    

    Live Java demo.

提交回复
热议问题