Skip to content

Commit

Permalink
added solution for 230. Kth Smallest Element in a BST
Browse files Browse the repository at this point in the history
  • Loading branch information
n1i9c9k9 committed Nov 2, 2024
1 parent 80c004e commit b590c83
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions C++/kth-smallest-element-in-a-bst.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int kthSmallest(TreeNode* root, int k) {
int count = 0;
return inorder(root, k, count);
}

private:
int inorder(TreeNode* node, int k, int& count) {
//Base case: Zero node
if(!node) return -1;

//Traverse left branch for kth smallest value:
int leftVal = inorder(node->left, k, count);
if(count == k) return leftVal;

//Process root node:
++count;
if(count == k) return node->val;

//Traverse right branch for kth smallest value:
return inorder(node->right, k, count);
}
};

0 comments on commit b590c83

Please sign in to comment.