Leetcode 653. Two Sum IV - Input is a BST 两数相加4 解题报告
2017-08-10 22:38
525 查看
恩,还是给一个数,问有给定的二叉搜索树,有没有两个数相加的和等于这个数
恩,我是最直接的做法,开空间记录出现过的数字。。
其实,这道题的思想,我猜应该是要求一个空间为O(1)的解法。。但是觉得这么做太复杂,就算了吧
恩,我是最直接的做法,开空间记录出现过的数字。。
其实,这道题的思想,我猜应该是要求一个空间为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] 653. Two Sum IV - Input is a BST 解题报告
- 【LeetCode】653. Two Sum IV - Input is a BST 解题报告
- 【LeetCode】653.Two Sum IV - Input is a BST(Easy)解题报告
- [LeetCode] 653. Two Sum IV - Input is a BST 两数之和之四 - 输入是二叉搜索树
- leetcode 653. Two Sum IV - Input is a BST
- leetcode 653. Two Sum IV - Input is a BST
- Leetcode653. Two Sum IV - Input is a BST
- 【LeetCode】653. Two Sum IV - Input is a BST
- leetcode653. Two Sum IV - Input is a BST
- LeetCode 653. Two Sum IV – Input is a BST
- <easy>LeetCode Problem -- 653. Two Sum IV - Input is a BST
- LeetCode - 653. Two Sum IV - Input is a BST
- leetcode 653. Two Sum IV - Input is a BST 中序遍历 + 深度优先遍历DFS
- Leetcode 653. Two Sum IV - Input is a BST
- LeetCode-653. Two Sum IV - Input is a BST
- leetcode专题—653. Two Sum IV - Input is a BST
- leetcode 653. Two Sum IV - Input is a BST
- LeetCode - 653. Two Sum IV - Input is a BST
- leetcode解题报告(22):Two Sum II - Input array is sorted
- Leetcode: 653. Two Sum IV - Input is a BST