Python实现"N叉树的层序遍历"的一种方法
给定一颗n叉树,返回按层级访问树节点的值。(从左到右,一层接一层)
例如,给定一颗三叉树
返回格式为:
[
[1],
[3,2,4],
[5,6]
]
注意:
树深最大为1000
节点总数最多为5000
1、注意题中,当前结点的子树是以列表的形式存放,所以代码对树层级结点的存放格式为双层列表
def levelOrder(self, root):
"""
:type root: Node
:rtype: List[List[int]]
"""
if not root:
return []
back = [] #函数返回的数据
curLevel = [[root]] #当前遍历树的层级,双层列表
while curLevel:
temp = [] #遍历当前层级时存放的临时结点值
nextLevel = [] #下一层树结点
for i in curLevel:
for j in i: #注意,层级节点存放为双层列表
temp.append(j.val)
if j.children: #当前结点是否存在子结点
nextLevel.append(j.children)
back.append(temp)
curLevel = nextLevel
return back
算法题来自:https://leetcode-cn.com/problems/n-ary-tree-level-order-traversal/description/