美文网首页
五. 搜索二叉树 2. Search Range in Bina

五. 搜索二叉树 2. Search Range in Bina

作者: 何大炮 | 来源:发表于2018-03-08 16:07 被阅读0次

    思路:
    感觉上,这道题要考虑的情况有些多,但是,我们只需要一个遍历,并将每个值与 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 Bina

          本文链接:https://www.haomeiwen.com/subject/gswdfftx.html