BST Inorder Predecessor
Given an array representing a Binary Search Tree (BST) in level-order and a target value, find the in-order predecessor of the target. The in-order predecessor is the largest value in the BST that is smaller than the target.
For example, in the BST [5, 3, 8, 1, 4, 7, 9], the predecessor of 5 is 4. The predecessor of 3 is 1. If the target is the smallest value in the tree (like 1), it has no predecessor — return 0. If the target does not exist in the tree, also return 0.
The in-order predecessor is an important concept in BST operations. It is used in deletion (replacing a node with its predecessor), finding the previous element in sorted order, and implementing floor queries. The predecessor is found by traversing the tree: if the target is larger than the current node, move right and update the candidate; otherwise, move left.
For the array-based representation, start at index 0. Maintain a candidate variable for the predecessor (initialized to 0). If the current node is less than the target, update the candidate and move right (2i+2). If greater, move left (2i+1). Continue until the index goes out of bounds.
Edge cases include an empty tree (return 0), a target smaller than every node (return 0), and a target equal to a node that has a left subtree (the predecessor is the maximum value in that left subtree).
Example Input & Output
Predecessor of 40 is 30
Min has no predecessor
1 is minimum, no predecessor
Predecessor of 10 is 5
Predecessor of 3 is 2
Algorithm Flow
Solution Approach
Traverse the BST, tracking the last node that is smaller than the target.
Initialize pred to 0 and i to 0 (root). While i is in bounds: if the current node is less than the target, it is a candidate for predecessor — update pred and move right (looking for a larger value that is still less than target). If the current node is greater than or equal to target, move left. After traversing all possible paths, return pred.
Time complexity is O(log n) for balanced trees, O(n) worst case. Space complexity is O(1).
Best Answers
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;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
