首页 > 其他分享 >【LeeCode】429.N叉树的层序遍历

【LeeCode】429.N叉树的层序遍历

时间:2023-01-13 23:31:09浏览次数:56  
标签:Node deque val 层序 List public 429 LeeCode children

【题目描述】

给定一个 N 叉树,返回其节点值的层序遍历。(即从左到右,逐层遍历)。

树的序列化输入是用层序遍历,每组子节点都由 null 值分隔(参见示例)。

​https://leetcode.cn/problems/n-ary-tree-level-order-traversal/​


【示例】

【LeeCode】429.N叉树的层序遍历_java

【代码】​​代码随想录​

package com.company;

import java.util.*;

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) {
List<List<Integer>> res = new LinkedList<>();
Deque<Node> deque = new LinkedList<>();
if (root == null) return res;
deque.offerLast(root);
while (!deque.isEmpty()){
int len = deque.size();
List<Integer> list = new LinkedList<>();
Node node = deque.pollFirst();
list.add(node.val);
List<Node> children = node.children;
if (children == null || children.size() == 0) continue;
for (Node child : children) {
if (child != null){
deque.offerLast(child);
}
}
res.add(list);
}
return res;
}
}
public class Test {
public static void main(String[] args) {

}
}

标签:Node,deque,val,层序,List,public,429,LeeCode,children
From: https://blog.51cto.com/u_13682316/6006805

相关文章