您的位置:首页 > 其它

[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 =
10
and 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);
}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: