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.
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
}
};
/** * 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
}
};
相关文章推荐
- 虚函数的作用
- 头文件管理(c++ primer plus -6th)
- OI本月刷水记录
- 一起做RGB-D SLAM(8) (关于调试与补充内容)
- HDU 2040 亲和数(水~)
- MongoDB (二) MongoDB 优点
- 多态的实现(内存分析)
- linux系统中读写流程
- 检查网页的不规范
- BTRFS文件系统管理
- MongoDB (一) MongoDB 介绍
- asp.net mvc验证总结(转)
- 项目所遇问题
- hdu1081 最大子矩阵
- old-boy_LINUX
- sourcetree换某个地址账号
- [leetcode] 151.Reverse Words in a String
- 学习《算法导论》第八章 计数排序 总结
- HealthKit 框架体系
- 红色警戒2修改器原理百科(五)