Sunday, July 17, 2016

Search Range in Binary Search Tree

I put it here as a reminder to read question carefully. In this example, it asks to return result in ascending order, so that in-order traversal should be first consideration.

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.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
 * 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) {
        // write your code here
        ArrayList<Integer> result = new ArrayList<Integer>();
        if (root == null)return result;
        //it requires to return values in ascendiing order, so choose in order for that purpose
        inOrderTraversal(root,k1,k2,result);
        return result;
    }
    //using post order to stop left and right earlier
    void inOrderTraversal(TreeNode root,int k1, int k2,ArrayList<Integer> al){
        if(root==null)return ;
        
        if(root.val>k1)inOrderTraversal(root.left,k1,k2,al);
        if(root.val>=k1 && root.val<=k2)
            al.add(root.val);
        if(root.val<k2)inOrderTraversal(root.right,k1,k2,al);
        
        return ;
    }
}

No comments: