Leetcode 653. Two Sum IV - Input is a BST 两数相加4 解题报告

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/MebiuW/article/details/77074511

恩,还是给一个数,问有给定的二叉搜索树,有没有两个数相加的和等于这个数

恩,我是最直接的做法,开空间记录出现过的数字。。

其实,这道题的思想,我猜应该是要求一个空间为O(1)的解法。。但是觉得这么做太复杂,就算了吧

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
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def findTarget(self, root, k):
        """
        :type root: TreeNode
        :type k: int
        :rtype: bool
        """
        exists = set()
        # DFS
        def helper(root):
            if root is None:
                return False
            if k - root.val in exists:
                return True
            else:
                exists.add(root.val)
                return helper(root.left) or helper(root.right)
        return helper(root)

猜你喜欢

转载自blog.csdn.net/MebiuW/article/details/77074511
今日推荐