0
点赞
收藏
分享

微信扫一扫

653. 两数之和 IV - 输入 BST(bfs)


文章目录

  • ​​Question​​
  • ​​Ideas​​
  • ​​Code​​

Question

​​653. 两数之和 IV - 输入 BST(bfs)​​

Ideas

bfs 用队列模拟 需要一个判重数组 (防止重复走)+ 拓展点

Code

O(N)

# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def findTarget(self, root: Optional[TreeNode], k: int) -> bool:
# 遍历二叉树
def bfs(root):
if not root:
return False
q = [root]
lis = []
while q:
t = q.pop(0)
lis.append(t.val)
if t.left:
q.append(t.left)
if t.right:
q.append(t.right)
n = len(lis)
map = []
for i in range(n):
if lis[i] not in map:
# dic[k-lis[i]] = i
map.append(k-lis[i])
else:
return True
return False
return bfs(root)


举报

相关推荐

0 条评论