lintcode: Search Range in Binary Search Tree
2016-03-22 21:38
204 查看
Given two values k1 and k2 (where k1 < k2) and a root pointer to a Binary Search Tree. Find all the keys of tree in range k1 to k2. i.e. print all x such that k1<=x<=k2 and x is a key of given BST. Return all the keys in ascending order.
中序遍历,判断每个key是否在[k1,k2]之间。
利用BST的特征,还可以进行剪枝,
中序遍历,判断每个key是否在[k1,k2]之间。
/** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */ class Solution { public: /** * @param root: The root of the binary search tree. * @param k1 and k2: range k1 to k2. * @return: Return all keys that k1<=key<=k2 in ascending order. */ void helper(vector<int> &res,TreeNode* node,int k1,int k2){ if(node->left){ helper(res,node->left,k1,k2); } if(node->val>=k1 && node->val<=k2){ res.push_back(node->val); } if(node->right){ helper(res,node->right,k1,k2); } } vector<int> searchRange(TreeNode* root, int k1, int k2) { // write your code here vector<int> res; if(root==NULL){ return res; } helper(res,root,k1,k2); return res; } };
利用BST的特征,还可以进行剪枝,
/** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */ class Solution { public: /** * @param root: The root of the binary search tree. * @param k1 and k2: range k1 to k2. * @return: Return all keys that k1<=key<=k2 in ascending order. */ void helper(vector<int> &res,TreeNode* node,int k1,int k2){ if(node->left && node->val>=k1){// helper(res,node->left,k1,k2); } if(node->val>=k1 && node->val<=k2){// res.push_back(node->val); } if(node->right && node->val<=k2){ helper(res,node->right,k1,k2); } } vector<int> searchRange(TreeNode* root, int k1, int k2) { // write your code here vector<int> res; if(root==NULL){ return res; } helper(res,root,k1,k2); return res; } };
相关文章推荐
- NYOJ 58 最小步数(BFS)
- 习题3 怎样与用户有效地沟通以获取用户的真实需求?
- 二叉树的生成和遍历
- Android中AsyncTask的使用
- poj_1163
- Global Variable Default Initialized 0
- Opengles绘图
- bzoj 3531 [SDOI2014]旅行
- 对三层架构的浅层理解
- 第十五讲-方法参数
- JQuery的Ajax跨域请求的
- 20160322servlet学习笔记Referer的防盗链应用
- RAID各级别特性详解
- 缅怀
- 酷欧天气实战
- 本周日记
- Better History(历史记录)
- 华硕笔记本使用老毛桃工具迅速重装系统(动作快估计就二十分钟,高手勿喷)
- 十大监视SQL Server性能的计数器
- 网易面试题 (第24题) 对字符串的一种编码