[Lintcode]11. Search Range in Binary Search Tree

11. Search Range in Binary Search Tree

  • 本题难度: Medium
  • Topic: Binary Tree

Description

Given a binary search tree and a range [k1, k2], return all elements in the given range.

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

20

/ 8 22
/ 4 12

我的代码

    def searchRange(self, root, k1, k2,res = []):
        # write your code here
        if root is None:
            return res
        if root.val>=k1 and root.val <= k2:
            res.append(root.val)
        return list(set(self.searchRange(root.left,k1,k2)+self.searchRange(root.right,k1,k2)))

别人的代码

    def searchRange(self, root, k1, k2):
    # write your code here
        res = []
        self.dfs(root, k1, k2, res)
        return res
    
    def dfs(self, root, k1, k2,res):
        
        if root != None:
            if root.val>=k1 and root.val<=k2:
                res.append(root.val)
        else:
            return
        
        if root.left != None:
            self.dfs(root.left, k1, k2, res)
        
        if root.right != None:
            self.dfs(root.right, k1, k2, res)

思路
感觉答案有错误。我自己觉得自己的思路没问题,但是通不过。

  • 时间复杂度
  • 出错

猜你喜欢

转载自www.cnblogs.com/siriusli/p/10381055.html