Given two values k1 and k2 (k1 < k2) and a pointer to the root of a BST. Find all the keys of tree in range [k1, k2] or k1<=x<=k2. Return all the keys in ascending order.
Do a binary search. If the root is in the search interval (low < root.val < high), search both left and right subtree. If the root.val < low, search right subtree. If the root.val > high, search left subtree.
Traverse Code
public ArrayList<Integer> searchRange(TreeNode root, int k1, int k2) {
ArrayList<Integer> results = new ArrayList<>();
bsearchRange(results, root, k1, k2);
Collections.sort(results);
return results;
}
private void bsearchRange(ArrayList<Integer> results, TreeNode root, int low, int high) {
if (root == null) {
return;
}
if (root.val >= low && root.val <= high) {
results.add(root.val);
bsearchRange(results, root.left, low, high);
bsearchRange(results, root.right, low, high);
} else if (root.val < low) {
bsearchRange(results, root.right, low, high);
} else {
bsearchRange(results, root.left, low, high);
}
}
We don't need to sort it. We can take advantaged of the binary search tree property - sorted. We can add in the nodes in a sorted order.