-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
79 lines (70 loc) · 2.09 KB
/
main.cpp
File metadata and controls
79 lines (70 loc) · 2.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// Source: https://leetcode.com/problems/kth-smallest-element-in-a-bst
// Title: Kth Smallest Element in a BST
// Difficulty: Medium
// Author: Mu Yang <http://muyang.pro>
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Given the `root` of a binary search tree, and an integer `k`, return the `k^th` smallest value (**1-indexed**) of all the values of the nodes in the tree.
//
// **Example 1:**
// https://assets.leetcode.com/uploads/2021/01/28/kthtree1.jpg
//
// ```
// Input: root = [3,1,4,null,2], k = 1
// Output: 1
// ```
//
// **Example 2:**
// https://assets.leetcode.com/uploads/2021/01/28/kthtree2.jpg
//
// ```
// Input: root = [5,3,6,2,4,null,null,1], k = 3
// Output: 3
// ```
//
// **Constraints:**
//
// - The number of nodes in the tree is `n`.
// - `1 <= k <= n <= 10^4`
// - `0 <= Node.val <= 10^4`
//
// **Follow up:** If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize?
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include <stack>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
// Iteration + Stack
//
// Use in-order traversal.
class Solution {
struct State {
TreeNode *root;
bool seen;
};
public:
int kthSmallest(TreeNode *root, int k) {
auto st = stack<State>();
st.push(State{root, false});
while (!st.empty()) {
auto [node, seen] = st.top();
st.pop();
if (!node) continue;
if (!seen) {
st.push(State{node->right, false});
st.push(State{node, true});
st.push(State{node->left, false});
continue;
}
--k;
if (k == 0) return node->val;
}
return 0; // should not reach here
}
};