转载链接: https://blog.youkuaiyun.com/romeo12334/article/details/81429618
给定一个N叉树,返回其节点值的层序遍历。 (即从左到右,逐层遍历)。
例如,给定一个 3叉树 :

返回其层序遍历:
[
[1],
[3,2,4],
[5,6]
]
说明:
- 树的深度不会超过
1000。 - 树的节点总数不会超过
5000。
思路:
树的层序遍历应该使用队列的迭代法,队列不为空时迭代。把根节点加入队列,队列不为空时,出队列元素,把此元素的子结点加入队列。
本题需要返回每一层的节点值,因此每次迭代需要遍历一层的节点,于是需要设置变量保存当前队列的长度,然后把这些元素全部拿出队列遍历。
附上python的列表相关操作:


![]()
python的列表即可用作栈也可用作队列。出队列元素(即移除第一个元素):list.pop(0)
- """
- # Definition for a Node.
- class Node(object):
- def __init__(self, val, children):
- self.val = val
- self.children = children
- """
- class Solution(object):
- def levelOrder(self, root):
- """
- :type root: Node
- :rtype: List[List[int]]
- """
- if not root:
- return [];
- que = []; // 保存节点的队列
- res = []; // 保存结果的列表
- que.append(root); // 根元素入队列
- while len(que): // 判断队列不为空
- l = len(que);
- sub = []; // 保存每层的节点的值
- for i in range(l):
- current = que.pop(0); // 出队列的当前节点
- sub.append(current.val);
- for child in current.children: // 所有子结点入队列
- que.append(child);
- res.append(sub); // 把每层的节点的值加入结果列表
- return res;
本文介绍了一种解决N叉树层序遍历问题的方法,通过使用队列的迭代法,实现从左到右逐层遍历节点值。文章详细解释了算法思路,并提供了Python代码实现。
282

被折叠的 条评论
为什么被折叠?



