Leetcode 653. Two Sum IV

来源:互联网 发布:知乎45个神回复 编辑:程序博客网 时间:2024/05/20 14:42

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

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

其实,这道题的思想,我猜应该是要求一个空间为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   7Target = 9Output: TrueExample 2:Input:     5   / \  3   6 / \   \2   4   7Target = 28Output: False
# Definition for a binary tree node.# class TreeNode(object):#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = Noneclass 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)
原创粉丝点击