Code Logo

BST Inorder Successor

Published at25 Jul 2026
Binary Search Tree Easy 0 views
Like0

Given a sorted array representing a BST's inorder traversal and a target value, find the next larger value (inorder successor). If none exists, return -1.

Since the array IS the inorder traversal, the successor of value v is the next element after v in the array. Find v's index and return the next element.

Example Input & Output

Example 1
Input
[10,20,30],10
Output
20
Explanation

Next after 10 is 20

Example 2
Input
[5,10,15,20],15
Output
20
Explanation

Next after 15 is 20

Example 3
Input
[1],1
Output
-1
Explanation

Single node, no successor

Example 4
Input
[1,2,3,4,5],3
Output
4
Explanation

Next after 3 is 4

Example 5
Input
[1,2,3,4,5],5
Output
-1
Explanation

5 is max, no successor

Algorithm Flow

Recommendation Algorithm Flow for BST Inorder Successor
Recommendation Algorithm Flow for BST Inorder Successor

Solution Approach

function solution(arr, target) {
  var idx = arr.indexOf(target);
  if (idx === -1 || idx === arr.length - 1) return -1;
  return arr[idx + 1];
}

Best Answers

java
class Solution {
    public int solution(int[] nums, int t) {
        for(int i=0;i<nums.length;i++){if(nums[i]==t&&i<nums.length-1)return nums[i+1];}
        return -1;
    }
}