标签:traversal 深度 badge child idt int second link rsa
429. N叉树的层序遍历
429. N-ary Tree Level Order Traversal
LeetCode429. N-ary Tree Level Order Traversal
题目描述
给定一个 N 叉树,返回其节点值的层序遍历。 (即从左到右,逐层遍历)。
例如,给定一个 3 叉树:
[
[1],
[3,2,4],
[5,6]
]
说明:
Java 实现
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
class Node {
public int val;
public List<Node> children;
public Node() {
}
public Node(int _val, List<Node> _children) {
val = _val;
children = _children;
}
}
class Solution {
public List<List<Integer>> levelOrder(Node root) {
List<List<Integer>> result = new LinkedList<>();
Queue<Node> queue = new LinkedList<>();
if (root == null) {
return result;
}
queue.offer(root);
while (!queue.isEmpty()) {
List<Integer> list = new LinkedList<>();
int size = queue.size();
for (int i = 0; i < size; i++) {
if (queue.peek().children != null) {
for (int j = 0; j < queue.peek().children.size(); j++) {
queue.offer(queue.peek().children.get(j));
}
}
list.add(queue.poll().val);
}
result.add(list);
}
return result;
}
}
参考资料
LeetCode 429. N叉树的层序遍历(N-ary Tree Level Order Traversal)
标签:traversal 深度 badge child idt int second link rsa
原文地址:https://www.cnblogs.com/hglibin/p/10849661.html