给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。
示例:
二叉树:[3,9,20,null,null,15,7],
返回其层序遍历结果:
[
[3],
[9,20],
[15,7]
]
Python 解答:
# 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 levelOrder(self, root: TreeNode) -> List[List[int]]:
res = []
if not root:
return res
temp = [root]
level = [root.val]
while temp:
res.append(level)
level = []
node = []
for i in range(len(temp)):
if temp[i].left:
node.append(temp[i].left)
level.append(temp[i].left.val)
if temp[i].right:
node.append(temp[i].right)
level.append(temp[i].right.val)
temp = node
return res
留言