forked from fengvyi/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
230. Kth Smallest Element in a BST.cpp
45 lines (42 loc) · 1.08 KB
/
230. Kth Smallest Element in a BST.cpp
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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
// Solution 1
class Solution {
public:
int DFS(TreeNode* root, int k, int& val, bool& found){
if(!root || found) return 0;
int left = DFS(root->left, k, val, found) + 1;
int right = DFS(root->right, k - left, val, found) + 1;
if(k == left) val = root->val, found = true;
return left + right - 1;
}
int kthSmallest(TreeNode* root, int k) {
int val = 0;
bool found = false;
DFS(root, k, val, found);
return val;
}
};
// Solution 2
class Solution {
public:
int kthSmallest(TreeNode* root, int k) {
stack<int>s;
reversedInOrder(root, s);
while(--k) s.pop();
return s.top();
}
void reversedInOrder(TreeNode* root, stack<int>& s){
if(!root) return;
reversedInOrder(root->right, s);
s.push(root->val);
reversedInOrder(root->left, s);
}
};