Search code examples
algorithmdata-structurestreebinary-treeinorder

Need help understanding inorder successor in binary search tree


I need help in understanding this interview question:

Q: Find an algorithm to find the next node (e.g., inorder successor) of a given node in a binary search tree where each node has a link to its parent.

Does parent mean the in-order predecessor or just the immediate parent? How would one create a tree where the nodes have a link to the root node or inorder predecessor? Any help in understanding the data structure and the program below would be appreciated...

the solution (As posted in a form) is shown below:

 public static TreeNode inorderSucc(TreeNode e) {
   if (e != null) {
     TreeNode p;

     // Found right children -> return 1st inorder node on right
     if (e.parent == null || e.right != null) {
       p = leftMostChild(e.right);
     } else {
       // Go up until we’re on left instead of right (case 2b)
       while ((p = e.parent) != null) {
         if (p.left == e) {
           break;
         }
         e = p;
       }
     }
     return p;
   }
   return null;
 }

 public static TreeNode leftMostChild(TreeNode e) {
   if (e == null) return null;
   while (e.left != null) e = e.left;
   return e;
 }

Solution

  • When nodes store pointers to their parents, it almost always maeans their immediate parents and not their successors. The question in this interview is then how to navigate the tree to find the inorder successor.

    The way to find an in order successor is to think about what would happen if you were to recursively do an in order walk of the tree, then to mimic what would happen next. In particular, the logic for an in order traversal always visits all of a node's left subtree, then the node itself, and then the right subtree. To find the in order successor, you need to see what case you're in.

    If the node you're currently at has a right subtree, then the in order successor of that tree must be the very first node that would be visited in that subtree during an in order traversal, which is the smallest element of that tree. You can find this by descending into the right subtree, then marching down the left spine of the tree until you find the leftmost node.

    If the node does not have a right subtree, then it's the largest node in some subtree. If you think about how the recursion works, the next step in an in order traversal would be to have all the recursive calls that just finished expanding their right subtrees return. Once this last frame returns, you'll visit the node of the first tree that expanded just its left subtree. Consequently, the in order successor of the node can be found by walking up the tree until you reach a node that's a left child. The parent of this node is then your successor. Alternatively, as an edge case, if you hit the root of the tree, that would also be your successor.

    Hope this helps!