653. 两数之和 IV - 输入 BST(bfs)
作者:互联网
文章目录
Question
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)
标签:right,BST,self,IV,bfs,lis,root,两数,left 来源: https://blog.csdn.net/qq_49821869/article/details/123638990