leetcode 653 二叉树的输入和

题目:
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
题解:
q,s=root and [root],set()
while q:
new=[]
for node in q:
if k-node.val in s:
return True
else:
s.add(node.val)
new.extend([child for child in [node.left,node.right] if child])
q=new
return False

猜你喜欢

转载自blog.csdn.net/weixin_44482648/article/details/86640181