Created
January 8, 2015 00:31
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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) { | |
ArrayList<Integer> res = new ArrayList<Integer>(); | |
searchRange(res, root, k1, k2); | |
return res; | |
} | |
private void searchRange(ArrayList<Integer> res, TreeNode root, int k1, int k2) { | |
if (root == null) | |
return; | |
if (k2 < root.val) { | |
searchRange(res, root.left, k1, k2); | |
return; | |
} | |
if (k1 > root.val) { | |
searchRange(res, root.right, k1, k2); | |
return; | |
} | |
if (k1 == Integer.MIN_VALUE) { | |
searchRange(res, root.left, k1, k2); | |
if (k2 >= root.val) { | |
res.add(root.val); | |
searchRange(res, root.right, k1, k2); | |
} | |
return; | |
} | |
if (k2 == Integer.MAX_VALUE) { | |
if (k1 <= root.val) { | |
searchRange(res, root.left, k1, k2); | |
res.add(root.val); | |
} | |
searchRange(res, root.right, k1, k2); | |
return; | |
} | |
searchRange(res, root.left, k1, Integer.MAX_VALUE); | |
res.add(root.val); | |
searchRange(res, root.right, Integer.MIN_VALUE, k2); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment