给定一个 N 叉树,返回其节点值的层序遍历。(即从左到右,逐层遍历)。
树的序列化输入是用层序遍历,每组子节点都由 null 值分隔(参见示例)。
示例 1:
输入:root = [1,null,3,2,4,null,5,6] 输出:[[1],[3,2,4],[5,6]]
示例 2:
输入:root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] 输出:[[1],[2,3,4,5],[6,7,8,9,10],[11,12,13],[14]]
提示:
1000
[0, 10^4]
之间1、递归(Recursion)
2、广度优先遍历(Breadth-First Traversal)
法一:
/*
// Definition for a Node.
class Node {
public int val;
public List children;
public Node() {}
public Node(int _val) {
val = _val;
}
public Node(int _val, List _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
private List> res = new ArrayList<>();
public List> levelOrder(Node root) {
// Recusion
// Time: O(n), n为节点数
// Space: O(n)
if (root != null) {
level(root, 1);
}
return res;
}
private void level(Node root, int depth) {
// 若当前行对应的列表不存在,加一个空列表
if (res.size() < depth) {
res.add(new ArrayList<>());
}
// 将当前节点的值加入当前行的 res 中
res.get(depth - 1).add(root.val);
// 递归处理子树
for (Node child : root.children) {
level(child, depth + 1);
}
}
}
法二:
/*
// Definition for a Node.
class Node {
public int val;
public List children;
public Node() {}
public Node(int _val) {
val = _val;
}
public Node(int _val, List _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public List> levelOrder(Node root) {
// 广度优先遍历(Breadth-First traversal)
// Time: O(n), n为节点数
// Space: O(n)
List> res = new ArrayList<>();
if (root == null) return res;
Deque deque = new ArrayDeque<>();
deque.addLast(root);
while (!deque.isEmpty()) {
int cnt = deque.size();
List level = new ArrayList<>();
for (int i = 0; i < cnt; i++) {
Node cur = deque.removeFirst();
level.add(cur.val);
for (Node children : cur.children) {
deque.addLast(children);
}
}
res.add(level);
}
return res;
}
}