653. Two Sum IV - Input is a BST 两个数的和,输入为平衡二叉树

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 1:

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

Target = 9

Output: True

Example 2:

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

Target = 28

Output: False

题意:给定二进制搜索树和目标数字,如果BST中存在两个元素,使得它们的和等于给定目标,则返回true。

  1. # Definition for a binary tree node.
  2. # class TreeNode(object):
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.left = None
  6. # self.right = None
  7. class Solution(object):
  8. def findTarget(self, root, k):
  9. """
  10. :type root: TreeNode
  11. :type k: int
  12. :rtype: bool
  13. """
  14. if (not root):
  15. return False
  16. s = set()
  17. queue = [root]
  18. while (queue):
  19. node = queue.pop(0)
  20. s.add(node.val)
  21. if(node.left):
  22. queue.append(node.left)
  23. if(node.right):
  24. queue.append(node.right)
  25. for num in s:
  26. if k - num in s and 2 * (k - num) != k:
  27. return True
  28. return False





posted @ 2017-08-06 20:28  xiejunzhao  阅读(779)  评论(0编辑  收藏  举报