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





相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-05-11
  • 2021-06-27
  • 2021-07-30
  • 2021-10-06
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-05-30
  • 2021-10-14
  • 2021-06-11
  • 2022-01-13
  • 2021-06-02
  • 2022-01-25
  • 2022-12-23
相关资源
相似解决方案