五. 搜索二叉树 2. Search Range in Binary Search Tree

五. 搜索二叉树 2. Search Range in Binary Search Tree_第1张图片

思路:
感觉上,这道题要考虑的情况有些多,但是,我们只需要一个遍历,并将每个值与 k1 k2 比较,满足了后放入list,最后将list 排序就行。

Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""


class Solution:
    """
    @param: root: param root: The root of the binary search tree
    @param: k1: An integer
    @param: k2: An integer
    @return: return: Return all keys that k1<=key<=k2 in ascending order
    """
    def searchRange(self, root, k1, k2):
        # write your code here
        self.list = []
        def find_all(root):
            if root:
                if root.val <= k2 and root.val >= k1: 
                    self.list.append(root.val)
                find_all(root.right)
                find_all(root.left)
        find_all(root)
        self.list.sort()
        
        return self.list

你可能感兴趣的:(五. 搜索二叉树 2. Search Range in Binary Search Tree)