描述
给定一个二叉查找树和范围[k1, k2]
。按照升序返回给定范围内的节点值。
样例
样例 1:
输入:
tree = {5}
k1 = 6
k2 = 10
输出:
[]
解释:没有数字介于6和10之间
样例 2:
输入:
tree = {20,8,22,4,12}
k1 = 10
k2 = 22
输出:
[12,20,22]
解释:[12,20,22]介于10和22之间
题目较简单,直接贴代码
/**
* 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 {
public List<Integer> searchRange(TreeNode root, int k1, int k2) {
// write your code here
List<Integer> list = new ArrayList<>();
if (root==null){
return list;
}
help(root,k1,k2,list);
return list;
}
public void help(TreeNode root, int k1, int k2,List<Integer> list){
if (root.left==null&&root.right==null) {
if (root.val<=k2&&root.val>=k1){
list.add(root.val);
}
return;
}
if (root.val<=k2&&root.val>=k1) list.add(root.val);
if (root.left!=null)
help(root.left,k1,k2,list);
if (root.right!=null)
help(root.right,k1,k2,list);
}
}