1 minute read

Given a binary search tree root containing unique values, and an integer t, return the value of the inorder successor of t. That is, return the smallest value greater than t in the tree.

Note: you can assume that the inorder successor exists.

Bonus: solve it in O(h)$timeand$O(1) space where h is the height of the tree.

Constraints

  • n ≤ 100,000 where n is the number of nodes in root

https://binarysearch.com/problems/Inorder-Successor

ExamplesPermalink

Example 1Permalink

Input

  • root =
example1Root 0 2 1 0 0->1 2 3 0->2 3 1 1->3 4 4 2->4
  • t = 2

Output

  • answer = 3

Example 2Permalink

Input

  • root =
example2Root 0 2 1 0 0->1 2 3 0->2 3 1 1->3 4 4 2->4
  • t = 1

Output

  • answer = 2

SolutionPermalink

/**
* class Tree {
* public:
* int val;
* Tree *left;
* Tree *right;
* };
*/
int solve(Tree *root, int t)
{
int res = INT_MAX;
while (root)
{
if (root->val > t)
{
res = std::min(res, root->val);
root = root->left;
}
else
{
root = root->right;
}
}
return res;
}

Leave a comment