码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2017-08-06 21:56:32      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:output   lin   http   flow   二叉树   ret   ica   arch   elf   

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





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

标签:output   lin   http   flow   二叉树   ret   ica   arch   elf   

原文地址:http://www.cnblogs.com/xiejunzhao/p/7295873.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!