Skip to content

Commit 958e6a8

Browse files
authored
Create Kth Smallest Element in a BST.cpp
1 parent 77d9085 commit 958e6a8

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

Kth Smallest Element in a BST.cpp

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8+
* };
9+
*/
10+
class Solution {
11+
public:
12+
int numNodes(TreeNode* root){
13+
if(root==NULL)
14+
return 0;
15+
16+
return (numNodes(root->left)+numNodes(root->right)+1);
17+
}
18+
int kthSmallest(TreeNode* root, int k) {
19+
int pos=numNodes(root->left);
20+
if(pos==k-1)
21+
return root->val;
22+
if(pos<k)
23+
return kthSmallest(root->right,k-pos-1);
24+
else if(pos>=k)
25+
return kthSmallest(root->left,k);
26+
}
27+
};

0 commit comments

Comments
 (0)