1. Standard Inorder Array Collection
Intuition
Perform a full inorder traversal of the BST, appending each visited node's data to an array. Since inorder traversal produces a sorted list of length N, the k-th largest element is located at index N - k. Return arr[N - k].
When to apply: Baseline comparison when tree size is small and code simplicity is preferred.
Algorithm
- Collect all elements in ascending order via inorder traversal into an array, then return the (N - k)-th element.
#include <iostream>#include <vector> struct Node { int data; Node* left; Node* right; Node(int val) : data(val), left(nullptr), right(nullptr) {}}; class Solution { void inorder(Node* root, std::vector<int>& vals) { if (!root) return; inorder(root->left, vals); vals.push_back(root->data); inorder(root->right, vals); }public: int kthLargest(Node* root, int k) { std::vector<int> vals; inorder(root, vals); int n = vals.size(); return vals[n - k]; }}; int main() { Node* root = new Node(20); root->left = new Node(8); root->right = new Node(22); root->left->left = new Node(4); root->left->right = new Node(12); root->left->right->left = new Node(10); root->left->right->right = new Node(14); Solution sol; std::cout << "3rd largest: " << sol.kthLargest(root, 3) << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(N) - Space complexity:
O(N) auxiliary space