File tree 1 file changed +42
-0
lines changed
Kth Smallest Element in a BST
1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Runtime: 20 ms, faster than 84.89% of C++ online submissions for Kth Smallest Element in a BST.
2
+ // Memory Usage: 21.5 MB, less than 72.76% of C++ online submissions for Kth Smallest Element in a BST.
3
+
4
+ /* *
5
+ * Definition for a binary tree node.
6
+ * struct TreeNode {
7
+ * int val;
8
+ * TreeNode *left;
9
+ * TreeNode *right;
10
+ * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11
+ * };
12
+ */
13
+
14
+ class Solution
15
+ {
16
+ public:
17
+ int kthSmallest (TreeNode* root, int k)
18
+ {
19
+ stack<TreeNode*> treeStack;
20
+ while (true )
21
+ {
22
+ while (root)
23
+ {
24
+ treeStack.push (root);
25
+ root = root->left ;
26
+ }
27
+ if (!treeStack.empty ())
28
+ {
29
+ root = treeStack.top ();
30
+ treeStack.pop ();
31
+
32
+ if (k == 1 )
33
+ break ;
34
+ else
35
+ --k;
36
+
37
+ root = root->right ;
38
+ }
39
+ }
40
+ return root->val ;
41
+ }
42
+ };
You can’t perform that action at this time.
0 commit comments