Code Logo

BST Inorder Predecessor

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 that exists in the array, find the inorder predecessor (the next smaller value). If the target is the minimum value, return -1.

Example Input & Output

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

Predecessor of 40 is 30

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

Min has no predecessor

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

1 is minimum, no predecessor

Example 4
Input
[5,10,15],10
Output
5
Explanation

Predecessor of 10 is 5

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

Predecessor of 3 is 2

Algorithm Flow

Recommendation Algorithm Flow for BST Inorder Predecessor
Recommendation Algorithm Flow for BST Inorder Predecessor

Solution Approach

function solution(arr, target) {
  var idx = arr.indexOf(target);
  if (idx <= 0) 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)return i>0?nums[i-1]:-1;}
        return -1;
    }
}