• [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:
    image.png

    We should return its level order traversal:

    [
         [1],
         [3,2,4],
         [5,6]
    ]
     ````
    
    **Note:**
    
    The depth of the tree is at most 1000.
    The total number of nodes is at most 5000.
    
    ## 解题思路
    这道题的思路跟二叉树的层次遍历一样,只不过多叉树需要多加一个遍历。我们需要一个队列,但是里面的节点是一个`List`集合。迭代的时候每次弹出的节点集合,我们需要遍历集合的所有子节点然后放入队列。此时结果集也增加一层。迭代整个过程
    最终运行结果战胜 `64.89 %` 的 java 提交记录,属于一般般的解法,还有很大的优化空间。提示下,更好的解法是用递归。
    代码如下:
    ```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 {
        public List<List<Integer>> levelOrder(Node root) {
            List<List<Integer>> resultList=new ArrayList<>();
            if(root==null) return resultList;
            Queue<List<Node>> queue=new LinkedList<>();
            List<Node> list=new ArrayList<>();
            list.add(root);
            queue.add(list);
            while(!queue.isEmpty()){
                List<Integer> result=new ArrayList<>();
                List<Node> childLayer=new ArrayList<>();
                List<Node> cur=queue.poll();
                for(Node i:cur){
                      if(i.children!=null&&i.children.size()>0){
                        childLayer.addAll(i.children);
                    }
                    result.add(i.val);
                }
             
                resultList.add(result);
                if(childLayer.size()>0){
                    queue.add(childLayer);
                }
            }
            return resultList;
        }
    }
    
  • 相关阅读:
    一致性hash算法
    运算符的重载
    HTTP协议详解
    SOA 新业务语言 新系统架构——什么是SOA
    js中几种实用的跨域方法原理详解
    Linq基于两个属性的分组
    BackBone结合ASP.NET MVC实现页面路由操作
    CSS学习总结
    单页应用 WebApp SPA 骨架 框架 路由 页面切换 转场
    2016年最值得学习的五大开源项目
  • 原文地址:https://www.cnblogs.com/rever/p/11251245.html
Copyright © 2020-2023  润新知