Inorder Successor in BST
Medium Trees
root is the root of a binary search tree: every value in a node's left subtree is smaller than the node's own value, and every value in its right subtree is larger, so no two nodes hold the same value. p is one of the tree's nodes; the examples name it by its value.
Read the tree's values from the smallest to the largest. The successor of p is the node that comes right after p in that order: the node holding the smallest value larger than p's. It can be a descendant of p or one of its ancestors.
Return the successor of p, or null if p holds the largest value in the tree and no node comes after it.
Example 1
Read from the smallest to the largest, the values are 5, 10, 12, 15, 18, 20, 25, 30, 35. 12 comes right after 10.
Example 2
Example 3
Constraints
1 ≤ number of nodes ≤ 10⁵-10⁹ ≤ node.val ≤ 10⁹- the tree is a binary search tree, so no two nodes hold the same value
pis a node of the tree
Solve it here
Write it in Python, Java or C++, run it on your own cases, and submit against hidden tests.
More Trees
- Lowest Common Ancestor of a Binary TreeAI round · Medium
- Validate Binary Search TreeAI round · Medium
- Binary Tree Level Order TraversalAI round · Medium
- Binary Tree Vertical Order TraversalMedium
- Find Leaves of Binary TreeMedium