Two sum IV:

Given a Binary Search Tree and a target number, return true if there exist two elements in the BST such that their sum is equal to the given target.

Example:

Input: 
    5
   / \
  3   6
 / \   \
2   4   7

Target = 9

Output: True

Solution:

class Solution:
    def findTarget(self, root, k):
        """
        :type root: TreeNode
        :type k: int
        :rtype: bool
        """
        if not root:
            return False
        bfs, s = [root], set()
        for i in bfs:
            if k-i.val in s:
                return True
            if i.left:
                bfs.append(i.left)
            if i.right:
                bfs.append(i.right)
            s.add(i.val)
        return False

Two sum IV - Input is a BST

相关文章: