File tree Expand file tree Collapse file tree 1 file changed +52
-0
lines changed
solutions/230.Kth_Smallest_Element_in_a_BST Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ * Author: illuz <iilluzen[at]gmail.com>
3
+ * File: AC_dfs_n.cpp
4
+ * Create Date: 2015-08-14 10:21:47
5
+ * Descripton:
6
+ */
7
+
8
+ #include < bits/stdc++.h>
9
+
10
+ using namespace std ;
11
+ const int N = 0 ;
12
+
13
+ // Definition for a binary tree node.
14
+ struct TreeNode {
15
+ int val;
16
+ TreeNode *left;
17
+ TreeNode *right;
18
+ TreeNode (int x) : val(x), left(NULL ), right(NULL ) {}
19
+ };
20
+
21
+ class Solution {
22
+ public:
23
+ int kthSmallest (TreeNode* root, int k) {
24
+ ans = 0 ;
25
+ flag = false ;
26
+ dfs (root, k);
27
+ return ans;
28
+ }
29
+
30
+ private:
31
+ int ans;
32
+ bool flag;
33
+ // this return size of a tree
34
+ int dfs (TreeNode* root, int k) {
35
+ // if found the ans
36
+ if (flag) return 0 ;
37
+ if (root == NULL ) return 0 ;
38
+ int leftsize = dfs (root->left , k);
39
+ if (k - leftsize == 1 ) {
40
+ ans = root->val ;
41
+ flag = true ;
42
+ }
43
+ int rightsize = dfs (root->right , k - leftsize - 1 );
44
+ return leftsize + rightsize + 1 ;
45
+ }
46
+ };
47
+
48
+ int main () {
49
+
50
+ return 0 ;
51
+ }
52
+
You can’t perform that action at this time.
0 commit comments