429. N-ary Tree Level Order Traversal
Link
難易度 : Medium
依照對岸Carl大神的練習順序,接下來會連做10題類似觀念的題目,題號如下 :
- 102.二叉树的层序遍历
- 107.二叉树的层次遍历II
- 199.二叉树的右视图
- 637.二叉树的层平均值
- 429.N叉树的层序遍历
- 515.在每个树行中找最大值
- 116.填充每个节点的下一个右侧节点指针
- 117.填充每个节点的下一个右侧节点指针II
- 104.二叉树的最大深度
- 111.二叉树的最小深度
那麼就直接開始吧!!!
這題擴充binary tree,讓子節點變成n個,但是萬變不如其宗,整體的做法還是一樣的。
class Solution
{
public List<List<Integer>> levelOrder(Node root)
{
Queue<Node> queue = new LinkedList<Node>();
List<List<Integer>> result = new ArrayList<List<Integer>>();
Node current;
if (root == null)
{
return result;
}
queue.add(root);
while (!queue.isEmpty())
{
int size = queue.size();
List<Integer> tuple = new ArrayList<Integer>();
// 遍尋此層數量的所有node 之後加入的不與理會
for (int i = 0; i < size; i++)
{
current = queue.poll();
tuple.add(current.val);
//遍尋所有子節點
for (Node node : current.children)
{
if (node != null)
{
queue.add(node);
}
}
}
if (tuple.size() > 0)
{
result.add(tuple);
}
}
return result;
}
}