Search Range in Binary Search Tree

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
For example, if k1 = 10 and k2 = 22, then your function should print 12, 20 and 22.

20

/ \

8 22

/ \

4 12

public ArrayList<Integer> searchRange(TreeNode root, int k1, int k2) {
    ArrayList<Integer> result = new ArrayList<>();
    searchRangeHelper(root, k1, k2, result);
    return result;
}

public void searchRangeHelper(TreeNode root, int min, int max,
                              ArrayList<Integer> result) {
    if (root == null || min > max) {
        return;
    }
    if (root.val < min) {
        searchRangeHelper(root.right, min, max, result);
    } else if (root.val > max) {
        searchRangeHelper(root.left, min, max, result);
    } else {
        searchRangeHelper(root.left, min, root.val - 1, result);
        result.add(root.val);
        searchRangeHelper(root.right, root.val + 1, max, result);
    }
}
FacebookTwitterGoogle+Share

Leave a Reply

Your email address will not be published. Required fields are marked *