卖萌的弱渣

I am stupid, I am hungry.

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

If k1 = 10 and k2 = 22, then your function should return [12, 20, 22].

1
2
3
4
5
    20
   /  \
  8   22
 / \
4   12

Solution

  • Time: O(n)
(Search-Range-in-Binary-Search-Tree.py) download
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:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""
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.
    """
    def searchRange(self, root, k1, k2):
        # write your code here
        result = []
        if root == None:
            return result

        if root.left != None:
            left_result = self.searchRange(root.left,k1,k2)
        else:
            left_result = []

        result = result + left_result

        if root.val>=k1 and root.val <=k2:
            result.append(root.val)

        if root.right != None:
            right_result = self.searchRange(root.right,k1,k2)
        else:
            right_result = []

        result = result + right_result

        return result