链接:http://www.lintcode.com/zh-cn/problem/search-range-in-binary-search-tree/
* 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> result = new ArrayList<>();
if (root == null) {
return null;
}
//递归定义
//递归拆解
if (root.left != null) {
result.addAll(searchRange(root.left, k1, k2));
}
if (root.val >= k1 && root.val <= k2) {
result.add(root.val);
}
if(root.right != null) {
result.addAll(searchRange(root.right,k1, k2));
}
return result;
//递归出口
}
}
本题使用递归方式解决,主要找到递归的拆解以及出口
需要注意的是对null值得判断
网友评论