# 429. N叉树的层序遍历

2019/7/24 11:34:30 人评论 次浏览 分类：学习教程

[
[1],
[3,2,4],
[5,6]
]

## 代码

`````` /**
* 土鳖做法：用父子队列来做，效率很低
* @param root
* @return
*/
public List<List<Integer>> levelOrder(Node root) {
List<List<Integer>> result = new ArrayList<>();
if(root == null){
return result;
}
parentQueue.offer(root);

int index = 0;
while (!parentQueue.isEmpty()) {
Node cur = parentQueue.poll();

while(result.size()<index+1){
}
result.get(index);
List<Node> childrens = cur.children;
for (Node children : childrens) {
sonQueue.offer(children);
}
if (parentQueue.isEmpty()) {
if (!sonQueue.isEmpty()) {
parentQueue = null;
parentQueue = sonQueue;
index++;
}
}
}
return result;
}

``````

``````    /**
*　递归方式
* @param root
* @return
*/
public List<List<Integer>> levelOrder2(Node root) {
List<List<Integer>> result = new ArrayList<>();
if(root == null){
return result;
}
levelOrder(root,0,result);
return result;
}

private void levelOrder(Node node,int depth,List<List<Integer>> result){
if(node == null){
return;
}

if(depth+1>result.size()){
}

for (Node child : node.children) {
levelOrder(child,depth+1,result);
}
}
``````

暂无相关的资讯...

-->