http://www.lintcode.com/en/problem/search-range-in-binary-search-tree/
Given two values k1 and k2 (where k1 < k2) and a root pointer to a Binary Search Tree. Find all the keys of tree in range k1 to k2. i.e. print all x such that k1<=x<=k2 and x is a key of given BST. Return all the keys in ascending order.
Example
If k1 = 10 and k2 = 22, then your function should return [12, 20, 22].
20
/
8 22
/
4 12
1 public class Solution {
2 /**
3 * @param root: param root: The root of the binary search tree
4 * @param k1: An integer
5 * @param k2: An integer
6 * @return: return: Return all keys that k1<=key<=k2 in ascending order
7 */
8
9 private List<Integer> res;
10 public List<Integer> searchRange(TreeNode root, int k1, int k2) {
11 // write your code here
12 res = new ArrayList<>();
13 helper(root, k1, k2);
14 return res ;
15 }
16
17 // the reason to use in order is this question ask you to keep ascending order
18 private void helper(TreeNode root, int k1 , int k2){
19 if (root == null) {
20 return ;
21 }
22 //branch pruning and recursive note since root == k1 or root == k2 already taken care of above
23 // else if root < k1, there is no need to go to left! every node of left in bst < root
24 if (root.val>k1) {
25 //go to left
26 helper(root.left, k1, k2) ;
27 }
28 //in order: note here is inclusive
29 if (k1 <= root.val && root.val <= k2 ) {
30 res.add(root.val);
31 }
32 // else if root > k2, then there is no need to go to right, every node in right > root
33 if (root.val<k2) {
34 //go to right
35 helper(root.right, k1, k2);
36 }
37 }
38 }