[Lintcode] Search Range in Binary Search Tree
2015-10-08 00:21
295 查看
Search Range in Binary Search Tree
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.Example
If k1 =
10and k2 =
22, then your function should return
[12, 20, 22].
20 / \ 8 22 / \ 4 12
SOLUTION :
这个的核心就是DFS,再说就是递归,所以这个题先定义一个递归函数,然后不停的递归判断就可以了,但是这个题要比普通DFS要有一些优化,因为很明显的是,(以root为指针dfs)当root.val < k1 OR root.val > k2 也就是说这个指针已经出了给定的条件了,这时候就没必要再往这个方向DFS了,再往下走结果也不会满足条件了。再仔细的说一下,就是,只有在root<k1或者root>k2的时候,不需要操作,反过来说:root > k1 或者(or)root < k2都需要操作,当root卡在k1,k2之间时候需要添加进result。然后就是这题为了方便DFS加入一个全局变量。 也可以不用全局result,而把result跟着helper函数走一遍就可以。具体的看代码:
public class Solution { /** * @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. */ private ArrayList<Integer> result;//定义一个全局变量 public ArrayList<Integer> searchRange(TreeNode root, int k1, int k2) { result = new ArrayList<Integer>(); helper(root, k1, k2); return result; } private void helper(TreeNode root, int k1, int k2){ if (root == null){ return; } if (k1 < root.val){ helper(root.left, k1, k2); } if (k1 <= root.val && root.val <= k2){ result.add(root.val); } if (k2 > root.val){ helper(root.right, k1, k2); } } }
相关文章推荐
- 模板方法模式
- stringstream的复制
- json字符串转换为JSONObject和JSONArray
- [网络]Unity的Socket通讯_2_数据传输
- Trump成功笔记4
- [Android] 点击listView的item无响应【解决办法】
- 图片懒加载
- Debian 用户名密码输入成功后重复登录
- C/C++代码中的笔误
- 第一阶段知识总结及问题反馈
- 外观模式
- BZOJ2725 : [Violet 6]故乡的梦
- 图片浏览器
- POJ 3349 Snowflake Snow Snowflakes(hash)
- UESTC 86 Divide (脑洞题+二进制)
- RTMP,RTSP,HLS比较与分析
- windows下主机名与IP地址的映射
- Trump成功笔记3
- (一)VBA基础——显示Excel的【开发工具】选项卡
- 适配器模式