力扣 102. 二叉树的层序遍历

前置

1
2
3
4
5
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right

bfs

1
2
3
4
5
6
7
8
9
10
11
12
13
def levelOrder(root):
if not root:
return []
res, cur = [], [root]
while cur:
tmp = []
for _ in range(len(cur)):
node = cur.pop(0)
tmp.append(node.val)
if node.left: cur.append(node.left)
if node.right: cur.append(node.right)
res.append(tmp)
return res
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2022 eightyninth
  • Visitors: | Views:

请我喝杯咖啡吧~

支付宝
微信