zoukankan      html  css  js  c++  java
  • 653. 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 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





  • 相关阅读:
    wait waitpid
    达梦备份还原
    sigprocmask阻塞信号
    sigaction信号处理
    dd命令
    linux系统启动过程
    cpio建立、还原备份档
    configure详解
    Git入门基础教程
    一篇文章了解Github和Git教程
  • 原文地址:https://www.cnblogs.com/xiejunzhao/p/7295873.html
Copyright © 2011-2022 走看看