I wrote the following code snippet to return the Kth smallest element in a BST:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int kthSmallest(TreeNode* root, int k) {
if(root==NULL)
return -2;
cout<<"Root value "<<root->val<<" and k value "<<k<<"\n";
kthSmallest(root->left, k-1);
if((k)==0)
return root->val;
kthSmallest(root->right, k-1);
}
};
I basically just do an inorder traversal of the tree and decrement the value of k during each recursive call. So, in this way, when the value of k equals 0, I have found the node and just return it.
Following is the output of my debugging statements:
Root value 1 and k value 3
Root value 2 and k value 2
Root value 4 and k value 1
Root value 8 and k value 0
Root value 9 and k value 0
Root value 5 and k value 1
Root value 10 and k value 0
Root value 11 and k value 0
Root value 3 and k value 2
Root value 6 and k value 1
Root value 12 and k value 0
Root value 7 and k value 1
I am unable to understand why the program keeps on executing even after k has become 0. What have I missed? I appreciate your help.
Edit: I don't think the question description is required, but if needed, it can be found here: LeetCode: Find Kth smallest element in a BST. Also, please note that I cannot edit the function prototype. Also, the question says that the k would be a valid number between 1 and BST's total number of elements.
kthSmallestreturns? - Some programmer dudekused during that recursive call was not0, then I just ignore it. - user8177388k == 0, but in the calling functionk != 0. Please learn how to use a debugger to step through your code line by line, stepping into the recursive calls. That should make it much clearer what happens. - Some programmer dudeKth smallest element. Ideally, I wish the value is returned only whenk==0. - user8177388