Use the inorder traversal and get all numbers in the BST in order. Then return the kth number.
/**
* 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) {
vector<int> nums;
inorder(root,nums);
return nums[k-1];
}
void inorder(TreeNode* root,vector<int>& nums)
{
if(!root)
return;
inorder(root->left,nums);
nums.push_back(root->val);
inorder(root->right,nums);
}
};
The following is the updated version with better run time, in which I do not need to traverse the whole tree. When I reach the kth smallest number, I just return that number to the top.
/**
* 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) {
return find(root,k);
}
int find(TreeNode* root,int &k)
{
if(!root)
return 0;
int l=find(root->left,k);
if(k==0)//the kth number is in the left subtree
return l;
k--;
if(k==0)//the kth number is this root
return root->val;
return find(root->right,k);//the kth number is in the right subtree
}
};