问题:给定一个二叉搜索树和一个目标数字,如果在树中存在两个元素,它们的和等于给定的目标,则返回True,否则返回False
思路:类似于Two Sum.只不过把链表换成了树,利用广度优先遍历即可。将已遍历过的树节点放到字典中
class Solution:
def findTarget(self, root, k):
if not root:
return False
a = [root]
dicts={}
while a:
one = a.pop(0)
if not dicts or ((k-one.val) not in dicts):
dicts[one.val]=one
else:
return True
if one.left:
a.append(one.left)
if one.right:
a.append(one.right)
return False