Get Keys In Binary Search Tree In Given Range

Get the list of keys in a given binary search tree in a given range[min, max] in ascending order, both min and max are inclusive.

Examples

5

/ \

3 8

/ \ \

1 4 11

get the keys in [2, 5] in ascending order, result is [3, 4, 5]

Corner Cases

  • What if there are no keys in the given range? Return an empty list in this case.

How is the binary tree represented?

We use the level order traversal sequence with a special symbol "#" denoting the null node.

For Example:

The sequence [1, 2, 3, #, #, 4] represents the following binary tree:

1

/ \

2 3

/

4

public class Solution {
  List<Integer> result = new ArrayList();

  public List<Integer> getRange(TreeNode root, int min, int max) {
    if (root == null) return new ArrayList();
    //base case 

    //recusive rule
    //check left child valid?
    //check self valid?
    //check right child valid?
    //return result
    getRange(root.left, min, max);

    int key = root.key;
    if (min <= key && key <= max){
      result.add(key);
    }

    getRange(root.right, min , max);
    
    return result;
  }
}

Last updated

Was this helpful?