【Lintcode】011.Search Range in Binary Search Tree
2024-09-08 14:26:40
题目:
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.
If k1 = 10
and k2 = 22
, then your function should return [12, 20, 22]
.
20
/ \
8 22
/ \
4 12
题解:
Solution 1 ()
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.
*/
vector<int> searchRange(TreeNode* root, int k1, int k2) {
vector<int> result; inOrder(result, root, k1, k2); return result;
} void inOrder(vector<int> &result, TreeNode* root, int k1, int k2) {
if (root == NULL) {
return;
}
if (root->val > k1) {
inOrder(result, root->left, k1, k2);
}
if (k1 <= root->val && root->val <= k2) {
result.push_back(root->val);
}
if (root->val < k2) {
inOrder(result, root->right, k1, k2);
}
}
};
最新文章
- JavaScript RegExp 对象(来自w3school)
- 基于ticket的rw锁
- Uva-11374-Airport Express
- java操作MySQL数据事务的简单学习
- winform 如何控制输入法
- 关于web页面JApplet打印小票
- 其他-pkuwc2019数学考试题目
- JMeter学习-042-JMeter BeanShell 脚本应用实例之正则应用:正则提取,批量获取测试数据
- mysql group_concat时间用法
- ios 审核未通过 相机相册权限问题
- 对Controller的单元测试
- awbeci网站之技术篇
- ajax数据流传参
- 算法笔记_146:TarJan算法的应用(Java)
- java 基础 --多态--009
- mysql 存储过程 编写注意事项
- Session接口常用方法
- spring scope 属性的取值
- 首次远程安装 GlassFish 后以远程 Web 方式访问其后台管理系统出现错误的解决方法(修订)
- Brackets前端开发编辑器