"""
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Solution:
def levelOrder(self, root: 'Node') -> List[List[int]]:
return [] if not root \
else [
[root.val],
*(sum(e, start=[]) for e in zip_longest(*(self.levelOrder(c) for c in root.children), fillvalue=[]))
]
/*
// Definition for a Node.
class Node {
public int val;
public List<Node> children;
public Node() {}
public Node(int _val) {
val = _val;
}
public Node(int _val, List<Node> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public List<List<Integer>> levelOrder(Node root) {
if (root == null) {
return new ArrayList<List<Integer>>();
}
List<List<Integer>> ans = new ArrayList<List<Integer>>();
Queue<Node> queue = new ArrayDeque<Node>();
queue.offer(root);
while (!queue.isEmpty()) {
int cnt = queue.size();
List<Integer> level = new ArrayList<Integer>();
for (int i = 0; i < cnt; ++i) {
Node cur = queue.poll();
level.add(cur.val);
for (Node child : cur.children) {
queue.offer(child);
}
}
ans.add(level);
}
return ans;
}
}
"""
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Solution:
def levelOrder(self, root: 'Node') -> List[List[int]]:
if root is None:
return []
que = deque()
que.append(root)
res = []
while que:
qlen = len(que)
level = []
while qlen > 0:
node = que.popleft()
for child in node.children:
que.append(child)
level.append(node.val)
qlen -= 1
res.append(level)
return res
"""
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Solution:
def levelOrder(self, root: 'Node') -> List[List[int]]:
if root is None:
return []
que = deque()
que.append((root, 0))
res = defaultdict(list)
while que:
node, level = que.popleft()
res[level].append(node.val)
for child in node.children:
que.append((child, level + 1))
res = list(res.values())
return res