3.4 Inorder Successor in BST
Logical Steps
- If p has a right tree, the in order successor is at the very left node of the right tree
- If p has no right tree, the successor is its parent or null
- Initiate successor cursor at null (if not being used, its gonna be at null)
- In order to not lost the position of root cursor, start looking of for parent by using binary search (since its a BST), whenever goes left, record the previous node as successor (parent)
- Search for successor in right tree by going to right node, and go all the way to the left
- Decide its in left tree, right tree or null
Code Template
public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
if (p == null || root == null)
return null;
TreeNode successor = null;
while (root.val != p.val && root != null) {
if (p.val > root.val) {
root = root.right;
}else{
successor = root;
root = root.left;
}
}
if (p.right != null) {
p = p.right;
while(p.left != null){
p = p.left;
}
return p;
}else{
return successor;
}
}
Common Mistakes
- When look for successors, initiate successor cursor at root: its will collide when root is p
TreeNode successor = root;
while (root.val != p.val && root != null) {
if (p.val > root.val) {
root = root.right;
}else{
successor = root;
root = root.left;
}
}
- Move successor cursor to root when traversing in tree to find P: parent is successor only when p is at left tree of parent, if root travels top-down to the right, it doesn't make sense to mark parent as in order succesor node
TreeNode successor = null;
while (root.val != p.val && root != null) {
if (p.val > root.val) {
successor = root
root = root.right;
}else{
successor = root;
root = root.left;
}
}