For this problem we’re given a root node of our BST and a second input that is going to be a positive non-zero integer k. Our solution should find the kth largest value in the BST. Meaning if we get the value 3 as k , then we would be trying to find the third largest value in the BST.
Reminder: A BST node is said to be valid if and only if it is strictly greater than its left child and greater than or equal to its right child.
Example:
Approach 1 (In-order traversal):
This approach uses in-order traversal to find the kth largest value. The idea is to traverse the BST in an in-order manner, which is not the most optimal, but would result in obtaining the BST values in sorted order and simply finding the kth value.
Implementation
Complexity Analysis
Time Complexity: O(n) — we are visiting every node in our BST
Space Complexity: O(n) — the recursive call stack is of length n and the array we created
Approach 2 (reverse in-order traversal):
Instead of visiting the nodes in order from smallest to larges like the last solution, it would be more efficient to visit the largest nodes in the BST first. To do this we switch the order of operations from left, visit, right to right, visit, left. Also, instead of saving all our nodes in an array, we can simply stop iterating at our kth value.
The only thing we’re storing or keeping track of is the number of nodes visited and the last value. This is unlike our last solution which stored the entire array of nodes.
Implementation
Complexity Analysis
Time Complexity: O(h+k) — in the worst case we will need to visit at most k nodes, but we also need to find the kth node and that node could potentially be further down our BST, thus the added h to account for the height of the tree
Space Complexity: O(h) — since this is a recursive algorithm we will have a call stack of length h.