
Question
Given a binary search tree and a node in it, find the in-order successor of that node in the BST.
Note: If the given node has no in-order successor in the tree, return null
.
Solution -- Iterative
Inorder result is an ascending array for BST. Thus, this problem can be transferred to find successor for a node in BST.
successor = first element that is greater than target node.
Consider two situations:
1. Target node has right child
2. Target node doesn't have right child
Trace back, find first node whose left child is in the path from target node to root.
For this situation:
1. If node has parent pointer, we just use parent pointer.
2. If node doesn't have parent pointer, we use stack.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
// Same question with finding successor in a BST
// 1. If p has right child, find minimum child in right subtree
// 2. If p doesn't have right child, find first ancestor whose left child is in the path from p to root.
TreeNode result = null;
if (p.right != null) {
result = p.right;
while (result.left != null) {
result = result.left;
}
} else {
Deque<TreeNode> stack = new LinkedList<TreeNode>();
TreeNode current = root;
// push to stack
while (current != p && current != null) {
stack.push(current);
if (p.val < current.val) {
current = current.left;
} else {
current = current.right;
}
}
// pop stack
TreeNode prev = p;
while (!stack.isEmpty()) {
TreeNode cur = stack.pop();
if (cur.left == prev) {
result = cur;
break;
}
prev = cur;
}
}
return result;
}
}
Solution 2 -- Recursive