Skip to content

Commit b590c83

Browse files
committed
added solution for 230. Kth Smallest Element in a BST
1 parent 80c004e commit b590c83

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

Diff for: C++/kth-smallest-element-in-a-bst.cpp

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
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+
int kthSmallest(TreeNode* root, int k) {
15+
int count = 0;
16+
return inorder(root, k, count);
17+
}
18+
19+
private:
20+
int inorder(TreeNode* node, int k, int& count) {
21+
//Base case: Zero node
22+
if(!node) return -1;
23+
24+
//Traverse left branch for kth smallest value:
25+
int leftVal = inorder(node->left, k, count);
26+
if(count == k) return leftVal;
27+
28+
//Process root node:
29+
++count;
30+
if(count == k) return node->val;
31+
32+
//Traverse right branch for kth smallest value:
33+
return inorder(node->right, k, count);
34+
}
35+
};

0 commit comments

Comments
 (0)