leetcode讲解--429. N-ary Tree Level Order Traversal

发布时间:2019-06-16 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了leetcode讲解--429. N-ary Tree Level Order Traversal脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

题目

Given an n-ary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

For example, given a 3-ary tree:

We should return its level order traversal:

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

Note:

  1. The depth of the tree is at most 1000.
  2. The total number of nodes is at most 5000.

[题目地址]https://leetcode.com/problems...

讲解

这道题我真的想了有很久,刚开始想用队列,但是发现不知道怎么分割每一层,于是就想还是用递归。后来越发想不明白,最后看了别人的解法。其实分割每一层是可以做到的。以后要多练习。

java代码

/*
// Definition for a Node.
class Node {
    public int val;
    public List<Node> children;

    public Node() {}

    public Node(int _val,List<Node> _children) {
        val = _val;
        children = _children;
    }
};
*/
class Solution {
    List<List<Integer>> result = new ArrayList<List<Integer>>();
    public List<List<Integer>> levelOrder(Node root) {
        if(root==null){
            return result;
        }
        Queue<Node> queue = new LinkedList<>();
        queue.offer(root);
        int children_num = 1;
        List<Integer> rootList = new ArrayList<Integer>();
        rootList.add(root.val);
        result.add(rootList);
        while(!queue.isEmpty()){
            List<Integer> list = new ArrayList<>();
            int count=0;
            for(int i=0;i<children_num;i++){
                Node now = queue.poll();
                if(now.children!=null){
                    for(Node node:now.children){
                        queue.offer(node);
                        list.add(node.val);
                        count++;
                    }
                }
            }
            children_num = count;
            if(list.size()>0){
                result.add(list);
            }
        }
        return result;
    }
}

脚本宝典总结

以上是脚本宝典为你收集整理的leetcode讲解--429. N-ary Tree Level Order Traversal全部内容,希望文章能够帮你解决leetcode讲解--429. N-ary Tree Level Order Traversal所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: