您的位置:首页 > 其它

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:

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加入集合中,继续循环遍历检查,直至结束。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode