LeetCode - 653. Two Sum IV - Input is a BST
2017-09-08 23:34
465 查看
Q:
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:
Example 2:
A:
备注:
自定义了一个方法,中序遍历二叉树节点,将节点值存至列表;
之后定义了一个空集合,再循环遍历节点列表,若存在k-val也就是目标值减去所得的节点值之后的结果也在集合内,则返回True,即列表中有两数之和为k;
若不在集合中,则将该val加入集合中,继续循环遍历检查,直至结束。
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
A:
# 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 """ def traversal(node): if not node: return None traversal(node.left) nodeList.append(node.val) traversal(node.right) nodeList = [] nodeSet = set() traversal(root) for val in nodeList: if k - val in nodeSet: return True nodeSet.add(val) return False
备注:
自定义了一个方法,中序遍历二叉树节点,将节点值存至列表;
之后定义了一个空集合,再循环遍历节点列表,若存在k-val也就是目标值减去所得的节点值之后的结果也在集合内,则返回True,即列表中有两数之和为k;
若不在集合中,则将该val加入集合中,继续循环遍历检查,直至结束。
相关文章推荐
- <easy>LeetCode Problem -- 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
- 2017.11.1 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 653. Two Sum IV - Input is a BST 两数相加4 解题报告
- 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
- LeetCode-653. Two Sum IV - Input is a BST
- leetcode 653. Two Sum IV - Input is a BST
- python--leetcode653. Two Sum IV - Input is a BST
- Leetcode653. 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