LeetCode-102、二叉树的层次遍历-中等
程序员文章站
2022-04-24 14:09:19
...
LeetCode-102、二叉树的层次遍历-中等
给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。
例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[9,20],
[15,7]
]
代码1:迭代
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
res = []
stack = [root]
while stack:
cur = []
nodes = []
for tmp in stack:
if tmp is None:
continue
else:
cur.append(tmp.val)
nodes.append(tmp.left)
nodes.append(tmp.right)
stack = nodes
if cur:
res.append(cur)
return res
代码2:递归
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
res = []
def recursion(cur, level):
if len(res) == level:
res.append([])
res[level].append(cur.val)
if cur.left:
recursion(cur.left, level+1)
if cur.right:
recursion(cur.right, level+1)
if root:
recursion(root, 0)
return res
上一篇: 单链表逆转(自己根据题干实现)