Kth Largest Element in BST
Kth Largest Element in BST is a easy trees & bst problem solved with the reverse inorder traversal pattern.
The best approach, optimal (reverse inorder, stop early), runs in O(h + k) time and O(h) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from inorder, then index from the end up.
Problem
Given the root of a BST and an integer k, return the k-th largest value. This is the mirror of Kth Smallest and teaches reverse inorder traversal.
Examples
Example 1
- Input
root = [4, 2, 9], k = 2- Output
4- Why
- Descending: 9, 4, 2.
Example 2
- Input
root = [9, null, 10], k = 1- Output
10
Constraints
1 <= k <= n <= 10^5; 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 10 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, then index from the end | O(n) | O(n) |
| Optimal (reverse inorder, stop early) | O(h + k) | O(h) |
1Inorder, then index from the end
O(n)O(n)Collect the sorted inorder list and return element n - k.
- list = inorder(root); return list.get(n - k).
class Solution {
public int kthLargest(TreeNode root, int k) {
List<Integer> vals = new ArrayList<>();
inorder(root, vals);
return vals.get(vals.size() - k);
}
private void inorder(TreeNode n, List<Integer> out) {
if (n == null) return;
inorder(n.left, out);
out.add(n.val);
inorder(n.right, out);
}
}class Solution:
def kthLargest(self, root: Optional[TreeNode], k: int) -> int:
vals: List[int] = []
self.inorder(root, vals)
return vals[len(vals) - k]
def inorder(self, n: Optional[TreeNode], out: List[int]) -> None:
if n is None:
return
self.inorder(n.left, out)
out.append(n.val)
self.inorder(n.right, out)class Solution {
public:
int kthLargest(TreeNode* root, int k) {
vector<int> vals;
inorder(root, vals);
return vals[vals.size() - k];
}
private:
void inorder(TreeNode* n, vector<int>& out) {
if (n == nullptr) return;
inorder(n->left, out);
out.push_back(n->val);
inorder(n->right, out);
}
};function kthLargest(root, k) {
const vals = [];
inorder(root, vals);
return vals[vals.length - k];
}
function inorder(n, out) {
if (n === null) return;
inorder(n.left, out);
out.push(n.val);
inorder(n.right, out);
}2Optimal (reverse inorder, stop early)
O(h + k)O(h)Traverse right subtree, node, left subtree, which visits values in descending order. Count visits and stop at the k-th.
- Push the right spine; pop; if --k == 0 return val; go left.
class Solution {
public int kthLargest(TreeNode root, int k) {
Deque<TreeNode> st = new ArrayDeque<>();
TreeNode cur = root;
while (true) {
while (cur != null) { st.push(cur); cur = cur.right; }
cur = st.pop();
if (--k == 0) return cur.val;
cur = cur.left;
}
}
}class Solution:
def kthLargest(self, root: Optional[TreeNode], k: int) -> int:
st = []
cur = root
while True:
while cur is not None:
st.append(cur)
cur = cur.right
cur = st.pop()
k -= 1
if k == 0:
return cur.val
cur = cur.leftclass Solution {
public:
int kthLargest(TreeNode* root, int k) {
stack<TreeNode*> st;
TreeNode* cur = root;
while (true) {
while (cur != nullptr) { st.push(cur); cur = cur->right; }
cur = st.top(); st.pop();
if (--k == 0) return cur->val;
cur = cur->left;
}
}
};function kthLargest(root, k) {
const st = [];
let cur = root;
while (true) {
while (cur !== null) { st.push(cur); cur = cur.right; }
cur = st.pop();
if (--k === 0) return cur.val;
cur = cur.left;
}
}Edge cases to test
- k = 1 (the maximum)
- k = n (the minimum)
Hints
Hint 1
Reverse inorder (right, node, left) visits values from largest to smallest.
FAQ
What is the best time complexity for Kth Largest Element in BST?
Optimal (reverse inorder, stop early) runs in O(h + k) time and O(h) extra space.
Which pattern does Kth Largest Element in BST use?
It is a trees & bst problem that uses the reverse inorder traversal pattern. Other problems with the same pattern: Kth Smallest Element in a BST.
Is there a brute force solution for Kth Largest Element in BST?
Yes. Inorder, then index from the end takes O(n) time and O(n) space. Collect the sorted inorder list and return element n - k.
Which edge cases should I test for Kth Largest Element in BST?
k = 1 (the maximum); k = n (the minimum).