给定一个 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]
之间package Solution429;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
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) {
List> result = new ArrayList>();
if (root == null) {
return result;
}
Queue queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int levelSize = queue.size();
List currentLevelNodes = new ArrayList<>(levelSize);
for (int i = 0; i < levelSize; i++) {
Node currentNode = queue.poll();
currentLevelNodes.add(currentNode.val);
if (currentNode.children != null && !currentNode.children.isEmpty()) {
queue.addAll(currentNode.children);
}
}
result.add(currentLevelNodes);
}
return result;
}
public List postorder(Node root) {
List list = new ArrayList<>();
helper(root, list);
return list;
}
public void helper(Node root, List list) {
if (root == null)
return;
if (root.children != null) {
for (Node child : root.children) {
helper(child, list);
}
}
list.add(root.val);
}
public static void main(String[] args) {
Solution sol = new Solution();
Node node5 = new Node(5);
node5.children = new ArrayList<>();
Node node6 = new Node(6);
node6.children = new ArrayList<>();
Node node3 = new Node(3);
node3.children = new ArrayList<>();
node3.children.add(node5);
node3.children.add(node6);
Node node2 = new Node(2);
node2.children = new ArrayList<>();
Node node4 = new Node(4);
node4.children = new ArrayList<>();
Node node1 = new Node(1);
node1.children = new ArrayList<>();
node1.children.add(node3);
node1.children.add(node2);
node1.children.add(node4);
System.out.println(sol.levelOrder(node1));
}
}