Skip to content

Commit fae6d4b

Browse files
authored
Merge pull request #54 from aryan57/master
Kth Smallest Element in a BST
2 parents 0b73fdf + fb7943a commit fae6d4b

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

Kth Smallest Element in a BST.cpp

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
8+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10+
* };
11+
*/
12+
class Solution {
13+
public:
14+
15+
int ans,z,cnt=0;
16+
17+
void inorder(TreeNode* root)
18+
{
19+
if(root==NULL)return;
20+
inorder(root->left);
21+
cnt++;
22+
if(cnt==z)ans=root->val;
23+
inorder(root->right);
24+
}
25+
26+
27+
int kthSmallest(TreeNode* root, int k)
28+
{
29+
z=k;
30+
inorder(root);
31+
return ans;
32+
}
33+
};

0 commit comments

Comments
 (0)