很简单的题,可以深度优先,也可广度优先。
# 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
"""
myset = set()
qu = [root]
while qu:
node = qu.pop(0)
if k - node.val in myset:
return True
else:
myset.add(node.val)
if node.left:
qu.append(node.left)
if node.right:
qu.append(node.right)
return False
网友评论