Search Range in Binary Search Tree
Question (LC.11)
Example
root20
/ \
8 22
/ \
4 12
Input: k1 = 10, k2 = 22
Return: [12, 20, 22]Analysis
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);
}
}D&C Code
Last updated