In Order Successor in Binary Search Tree

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

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

17条回答
  •  北荒
    北荒 (楼主)
    2020-11-27 04:48

    The general way depends on whether you have a parent link in your nodes or not.

    If you store the parent link

    Then you pick:

    1. The leftmost child of the right child, if your current node has a right child. If the right child has no left child, the right child is your inorder successor.
    2. Navigate up the parent ancestor nodes, and when you find a parent whose left child is the node you're currently at, the parent is the inorder successor of your original node.

    If you have right child, do this approach (case 1 above):

    inorder-when-right-child

    If you don't have a right child, do this approach (case 2 above):

    inorder-when-no-right-child

    If you don't store the parent link

    Then you need to run a complete scan of the tree, keeping track of the nodes, usually with a stack, so that you have the information necessary to basically do the same as the first method that relied on the parent link.

提交回复
热议问题