This code is to return 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 fid;
void inorder(TreeNode* node, int& fid, int& k) {
if (!node) return;
inorder(node->left, fid, k);
if (!k) return;
fid = node->val;
k--;
inorder(node->right, fid, k);
}
int kthSmallest(TreeNode* root, int k) {
inorder(root, fid, k);
return fid;
}
};
It gave the correct answer. I thought I could simplify the code by combining inorder function and kthSmallest function together.
class Solution {
public:
int fid;
int kthSmallest(TreeNode* root, int k) {
if (!root) return fid;
kthSmallest(root->left, k);
if (!k) return fid;
fid = root->val;
k--;
kthSmallest(root->right, k);
return fid;
}
};
It gave the wrong answer. If I input BST{2,1} k=1, it will return 2 instead of 1. I couldn't figure out why two codes are different. Thanks for your help!