Loading...
You are given a binary search tree root containing unique values, and an integer t that occurs in the tree. Return the smallest value in the tree that is greater than t.
You can assume such a value exists.
Your function receives root as a TreeNode. The node type is provided for you, with val, left, and right fields.
The examples below write the tree as its level-order traversal, where null marks a missing child of a listed node and trailing nulls are omitted. That is only how the input is displayed; the decoding is done for you.
root, n, is in the range [2,105].Node.val ≤109Node.val are unique.t occurs in the tree, and t is not the maximum value in the tree.root is a valid binary search tree: every node's value is greater than every value in its left subtree and less than every value in its right subtree.Starting at the root `5`, since `5 > 4` it becomes the best candidate so far, and the walk continues left looking for something smaller but still greater than `4`. That side runs out without finding one, so `5` is the answer.
Starting at the root `5`, since `5` is not greater than `5` the walk goes right to `8`, the new best candidate. Going left from `8` reaches `7`, still greater than `5` and closer, so `7` replaces `8` as the final answer.
The root `2` is greater than `1`, so it is the smallest value in the tree exceeding `1`.
Click "Run" to test with sample cases or "Submit" to run all tests.