Python Simple O(n) DFS


  • 2
    def findTarget(self, root, k):
        a = set()
        self.f = False
        def dfs(root, k):
            if not root:
                return 
            if root.val not in a:
                a.add(k - root.val)
            else:
                self.f = True
            dfs(root.left, k)
            dfs(root.right, k)
        dfs(root, k)
        return self.f

  • 2
    S

    Since it's a BST, a better solution would take advantage of it by using two pointers pointing at the smallest and the largest.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.