Problem Description
Given a node in a binary search tree where each node has a pointer to its parent, find the in-order successor of that node. The in-order successor is the node with the smallest key greater than the current node's value. If no such node exists, return null.
Key Insights
- If the given node has a right child, the successor is the leftmost node in the right subtree.
- If the node does not have a right child, move up the tree using the parent pointer until you find a node that is a left child of its parent. That parent node is the successor.
- If no suitable parent is found, the given node is the largest element and its successor is null.
Space and Time Complexity
Time Complexity: O(h), where h is the height of the tree. Space Complexity: O(1) using a constant amount of extra space.
Solution
We leverage the properties of a BST along with parent pointers. The algorithm first checks if the node has a right subtree. If yes, it finds the leftmost node in that subtree which is the in-order successor. If there is no right subtree, we traverse up using parent pointers until we find a node that is the left child of its parent, which indicates that the parent's value is the next greater element in the in-order traversal.