Skip to content

Commit 2159733

Browse files
Add files via upload
1 parent 96376a3 commit 2159733

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
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+
};

0 commit comments

Comments
 (0)