lintcode-medium-Search Range in Binary Search Tree
2016-04-05 12:48
387 查看
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 =
[/code]
Example
If k1 =
10and k2 =
22, then your function should return
[12, 20, 22].
20 / \ 8 22 / \ 4 12
[/code]
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */ 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. */ public ArrayList<Integer> searchRange(TreeNode root, int k1, int k2) { // write your code here ArrayList<Integer> result = new ArrayList<Integer>(); if(root == null) return result; if(root.left == null && root.right == null){ if(root.val >= k1 && root.val <= k2){ result.add(root.val); return result; } else return result; } ArrayList<Integer> left = searchRange(root.left, k1, k2); result.addAll(left); if(root.val >= k1 && root.val <= k2) result.add(root.val); ArrayList<Integer> right = searchRange(root.right, k1, k2); result.addAll(right); return result; } }
相关文章推荐
- 一篇让Java程序猿随时可以翻看的Oracle总结
- Android模拟器对应的电脑快捷键说明
- Strongart(苏州于志成)
- python路径相关的函数os.listdir(dirname):列出dirname下的目录和文件
- More Resource Types
- Ecplise必须知道的配置
- 数据持久化(五)之CoreData
- 界面安全性系列1-CSRF攻击
- istream, outstream使用及常见错误
- Style Resource
- appium Explicit Waits
- iis启动网站提示 文件正在使用
- bzoj:2428: [HAOI2006]均分数据 模拟退火
- 数据库行转列及逗号分隔转行
- 女博士嫁农村十年:代际贫穷轮回 看不到前景
- matlab 扩大虚拟内存
- mac下忘记mysql密码, 重新设置mysql密码
- 排序后数组中相邻两数的最大值
- python os.path模块常用方法详解
- github不小心同步覆盖了本地文件