您的位置:首页 > 其它

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

2017-08-10 22:38 525 查看
恩,还是给一个数,问有给定的二叉搜索树,有没有两个数相加的和等于这个数

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

其实,这道题的思想,我猜应该是要求一个空间为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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode