← Home

230. Kth Smallest Element in a BST

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
two pointersC++Markdown
230

Let's make this one less mysterious. For 230. Kth Smallest Element in a BST, the solution in this repository is mainly a two pointers solution.

Guide

What?

Before optimizing anything, pin down what information is still useful after each move. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: two pointers, stack, sliding window.

Guide

When?

Reach for this shape when a direct simulation would work logically but waste time revisiting the same information. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are inOrder, kthSmallest.

Guide

Why?

The solution works because it narrows the problem until every update has a clear reason to exist.

  • The stack stores unfinished context, which is usually the cleanest way to handle nested or monotonic structure.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Initialize the memory or helper structure.
  2. Process candidates in the order the invariant expects.
  3. Update the answer only when the current state is valid.
  4. Return the value that represents the fully processed input.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(H+k), space: O(H+k), where H is the height of the tree, it could be N or logN
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Runtime: 16 ms, faster than 96.43% of C++ online submissions for Kth Smallest Element in a BST.
02//Memory Usage: 20.9 MB, less than 100.00% of C++ online submissions for Kth Smallest Element in a BST.
03
04/**
05 * Definition for a binary tree node.
06 * struct TreeNode {
07 *     int val;
08 *     TreeNode *left;
09 *     TreeNode *right;
10 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11 * };
12 */
13class Solution {
14public:
15    int k;
16    
17    int inOrder(TreeNode* node){
18        if(!node) return -1;
19        int lval = inOrder(node->left);
20        if(lval != -1) return lval;
21        if(--k == 0){
22            return node->val;
23        }
24        int rval = inOrder(node->right);
25        if(rval != -1) return rval;
26        return -1;
27    };
28    
29    int kthSmallest(TreeNode* root, int k) {
30        this->k = k;
31        return inOrder(root);
32    }
33};
34
35//Approach 2: Iteration
36//Runtime: 24 ms, faster than 51.38% of C++ online submissions for Kth Smallest Element in a BST.
37//Memory Usage: 20.7 MB, less than 100.00% of C++ online submissions for Kth Smallest Element in a BST.
38//time: O(H+k), space: O(H+k), where H is the height of the tree, it could be N or logN
39/**
40 * Definition for a binary tree node.
41 * struct TreeNode {
42 *     int val;
43 *     TreeNode *left;
44 *     TreeNode *right;
45 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
46 * };
47 */
48class Solution {
49public:
50    int kthSmallest(TreeNode* root, int k) {
51        stack<TreeNode*> stk;
52        TreeNode* cur = root;
53        
54        do{
55            while(cur){
56                stk.push(cur);
57                cur = cur->left;
58            }
59
60            cur = stk.top(); stk.pop();
61
62            if(--k == 0) return cur->val;
63            // cout << cur->val << " ";
64            cur = cur->right;
65            
66        //when stk not empty or cur not null, we should continue the loop
67        }while(!stk.empty() || cur);
68        // cout << endl;
69        
70        return -1;
71    }
72};

Cost

Complexity

Time
O(H+k), space: O(H+k), where H is the height of the tree, it could be N or logN
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.