Monday, October 2, 2017

In-order successor of given node in the BST

Given a binary search tree and a node in it, find the in-order successor of that node in the BST.


There are just two cases:
  1. The easier one: p has right subtree, then its successor is just the leftmost child of its right subtree;
  2. The harder one: p has no right subtree, then a traversal is needed to find its successor.

TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
 4         if (p.right!=NULL) 
               return leftMost(p -> right);
 5         TreeNode succ = NULL;
 6         while (root!=null) {
 7             if (p.val < root.val) {
 8                 succ = root;
 9                 root = root.left;
10             }
11             else if (p.val > root.val)
12                 root = root.right; 
13             else 
                   break;
14         }
15         return suc;
16     }

No comments:

Post a Comment