Reference: LeetCode EPI 9.9
Difficulty: Medium
Note: EPI 9.9 does not assume that the tree is a BST, which means we don’t use values.
Problem
Given a binary search tree and a node in it, find the in-order successor of that node in the BST.
The successor of a node
p
is the node with the smallest key greater thanp.val
.
You will have direct access to the node but not to the root of the tree. Each node will have a reference to its parent node.
Note:
- If the given node has no in-order successor in the tree, return
null
. - It’s guaranteed that the values of the tree are
unique
. - Remember that we are using the
Node
type instead ofTreeNode
type so their string representation are different.
Follow up: Could you solve it without looking up any of the node’s values
?
Analysis
Methods:
- Brute-Force (Value-based)
- Since it is BST, we do
inorder traversal
. Return the node after the target nodex
. - But you have to use
parent
links to find the root first. - Time: $O(h)$
- Space: $O(1)$
- Since it is BST, we do
- Iteration
- If the node has a right child, and hence its successor is somewhere lower in the tree. Go to the right once and then as many times to the left as you could. Return the node you end up with.
- Node has no right child, and hence its successor is somewhere upper in the tree. Go up till the node that is left child of its parent. The answer is the parent.
- Time: $O(h)$
- Space: $O(1)$
Code
Iteration
Note:
- Base case checking matters here, since it uses
x.right
.
1 | public Node inorderSuccessor(Node x) { |