题目描述:
给定两个值 k1 和 k2(k1 < k2)和一个二叉查找树的根节点。找到树中所有值在 k1 到 k2 范围内的节点。即打印所有x (k1 <= x <= k2) 其中 x 是二叉查找树的中的节点值。返回所有升序的节点值。
样例
如果有 k1 = 10 和 k2 = 22, 你的程序应该返回 [12, 20, 22].
20
/ \
8 22
/ \
4 12
解题思路:
用递归实现,root在k1和k2之间,则将root的值放入list中,再递归左右子树,若root.val
/**
* 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> list = new ArrayList<>();
public ArrayList<Integer> searchRange(TreeNode root,int k1,int k2){
ArrayList<Integer> list=new ArrayList<Integer>();
helper(root,k1,k2,list);
Collections.sort(list);
return list;
}
public void helper(TreeNode root, int k1, int k2,ArrayList<Integer> list) {
if(root==null)
return;
if((root.val>=k1)&& (root.val<=k2)){
list.add(root.val);
helper(root.left,k1,k2,list);
helper(root.right,k1,k2,list);
}
if(root.val<k1){
helper(root.right,k1,k2,list);
}
if(root.val>k2){
helper(root.left,k1,k2,list);
}
}
}
另外一种写法:
/**
* 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> list = new ArrayList<>();
public ArrayList<Integer> searchRange(TreeNode root, int k1, int k2) {
if(null==root) return list;
if((root.val>=k1)&& (root.val<=k2)){
list.add(root.val);
searchRange(root.left,k1,k2);
searchRange(root.right,k1,k2);
}
else if(root.val<k1){
searchRange(root.right,k1,k2);
}
else if(root.val>k2){
searchRange(root.left,k1,k2);
}
Collections.sort(list);
return list;
}
}
两种写法类似,但是不同的是递归的参数设置。区别在于list的是递归参数,还是全局变量。