11. 二叉查找树中搜索区间
给定一个二叉查找树和范围[k1, k2]。按照升序返回给定范围内的节点值。
样例
样例 1:
输入:{5},6,10
输出:[]
5
它将被序列化为 {5}
没有数字介于6和10之间
样例 2:
输入:{20,8,22,4,12},10,22
输出:[12,20,22]
解释:
20
/ \
8 22
/ \
4 12
它将被序列化为 {20,8,22,4,12}
[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 {
/**
* @param root: param root: The root of the binary search tree
* @param k1: An integer
* @param k2: An integer
* @return: return: Return all keys that k1<=key<=k2 in ascending order
*/
public List<Integer> searchRange(TreeNode root, int k1, int k2) {
// write your code here
List<Integer> ret=new ArrayList<>();
preSerialization(root , ret, k1, k2);
return ret;
}
public void preSerialization(TreeNode treeNode ,List<Integer> ret, int k1, int k2){
if(treeNode != null){
if (k1<=treeNode.val&&treeNode.val<=k2){
ret.add(treeNode.val);
}
preSerialization(treeNode.left, ret, k1, k2);
preSerialization(treeNode.right, ret, k1, k2);
}
}
}
来源:https://blog.csdn.net/xwdrhgr/article/details/102778267