/**
* 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> searchRange(TreeNode root, int k1, int k2) {
// write your code here
ArrayList<Integer> result = new ArrayList<Integer>();
helper(root, k1, k2, result);
return result;
}
private void helper(TreeNode root, int min, int max, List<Integer> result) {
if (root == null) {
return;
}
if (root.val > min && root.val < max) {
helper(root.left, min, max, result);
result.add(root.val);
helper(root.right, min, max, result);
} else if (root.val <= min) {
if (root.val == min) {
result.add(root.val);
}
helper(root.right, min, max, result);
} else if (root.val >= max) {
helper(root.left, min, max, result);
if (root.val == max) {
result.add(root.val);
}
}
}
}
2016年9月1日星期四
[LintCode] 11. Search Range in Binary Search Tree
订阅:
博文评论 (Atom)
没有评论:
发表评论