您的位置:首页 > 其它

leetcode 230: Kth Smallest Element in a BST

2015-08-30 14:13 344 查看
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
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: