Inorder predecessor
Inorder predecessor is a medium trees & bst problem solved with the miscellaneous bst questions pattern.
The best approach, optimal (walk down with a candidate), runs in O(h) time and O(1) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from inorder list up.
Problem
Given a BST and a value key, return the inorder predecessor of key: the node with the largest value smaller than key, or null if there is none.
Examples
Example 1
- Input
root = [5, 3, 6, 2, 4, null, null, 1], key = 4- Output
3
Example 2
- Input
same tree, key = 1- Output
null- Why
- 1 is the smallest value.
Constraints
- The tree has
1to10^4nodes; unique values.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (2 examples, or your own). Submit also runs 9 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Inorder list | O(n) | O(n) |
| Optimal (walk down with a candidate) | O(h) | O(1) |
1Inorder list
O(n)O(n)Collect the inorder traversal and return the node just before the one with value key.
- Inorder list; find key; return the previous node.
class Solution {
public TreeNode inorderPredecessor(TreeNode root, int key) {
List<TreeNode> nodes = new ArrayList<>();
inorder(root, nodes);
for (int i = 1; i < nodes.size(); i++) if (nodes.get(i).val == key) return nodes.get(i - 1);
return null;
}
private void inorder(TreeNode n, List<TreeNode> out) {
if (n == null) return;
inorder(n.left, out);
out.add(n);
inorder(n.right, out);
}
}class Solution:
def inorderPredecessor(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]:
nodes: List[TreeNode] = []
self.inorder(root, nodes)
for i in range(1, len(nodes)):
if nodes[i].val == key:
return nodes[i - 1]
return None
def inorder(self, n: Optional[TreeNode], out: List[TreeNode]) -> None:
if n is None:
return
self.inorder(n.left, out)
out.append(n)
self.inorder(n.right, out)class Solution {
public:
TreeNode* inorderPredecessor(TreeNode* root, int key) {
vector<TreeNode*> nodes;
inorder(root, nodes);
for (size_t i = 1; i < nodes.size(); i++) if (nodes[i]->val == key) return nodes[i - 1];
return nullptr;
}
private:
void inorder(TreeNode* n, vector<TreeNode*>& out) {
if (n == nullptr) return;
inorder(n->left, out);
out.push_back(n);
inorder(n->right, out);
}
};function inorderPredecessor(root, key) {
const nodes = [];
inorder(root, nodes);
for (let i = 1; i < nodes.length; i++) if (nodes[i].val === key) return nodes[i - 1];
return null;
}
function inorder(n, out) {
if (n === null) return;
inorder(n.left, out);
out.push(n);
inorder(n.right, out);
}2Optimal (walk down with a candidate)
O(h)O(1)The predecessor is the largest value smaller than key. From the root: if node.val < key, remember it and go right to look for a larger one; otherwise go left.
- pred = null; cur = root.
- If cur.val < key: pred = cur; cur = cur.right. Else cur = cur.left.
class Solution {
public TreeNode inorderPredecessor(TreeNode root, int key) {
TreeNode pred = null, cur = root;
while (cur != null) {
if (cur.val < key) { pred = cur; cur = cur.right; }
else cur = cur.left;
}
return pred;
}
}class Solution:
def inorderPredecessor(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]:
pred, cur = None, root
while cur is not None:
if cur.val < key:
pred = cur
cur = cur.right
else:
cur = cur.left
return predclass Solution {
public:
TreeNode* inorderPredecessor(TreeNode* root, int key) {
TreeNode *pred = nullptr, *cur = root;
while (cur != nullptr) {
if (cur->val < key) { pred = cur; cur = cur->right; }
else cur = cur->left;
}
return pred;
}
};function inorderPredecessor(root, key) {
let pred = null, cur = root;
while (cur !== null) {
if (cur.val < key) { pred = cur; cur = cur.right; }
else cur = cur.left;
}
return pred;
}Edge cases to test
- key is the minimum (no predecessor)
- key has a left subtree
Hints
Hint 1
Mirror of the successor: going right records a candidate.
FAQ
What is the best time complexity for Inorder predecessor?
Optimal (walk down with a candidate) runs in O(h) time and O(1) extra space.
Which pattern does Inorder predecessor use?
It is a trees & bst problem that uses the miscellaneous bst questions pattern. Other problems with the same pattern: Inorder Successor in BST, Floor in BST, Ceil in BST.
Is there a brute force solution for Inorder predecessor?
Yes. Inorder list takes O(n) time and O(n) space. Collect the inorder traversal and return the node just before the one with value key.
Which edge cases should I test for Inorder predecessor?
key is the minimum (no predecessor); key has a left subtree.