zoukankan      html  css  js  c++  java
  • [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;
        }
    }
    
  • 相关阅读:
    左孩子右兄弟的字典树
    UVA 1401 Remember the Word
    HDOJ 4770 Lights Against Dudely
    UvaLA 3938 "Ray, Pass me the dishes!"
    UVA
    Codeforces 215A A.Sereja and Coat Rack
    Codeforces 215B B.Sereja and Suffixes
    HDU 4788 Hard Disk Drive
    HDU 2095 find your present (2)
    图的连通性问题—学习笔记
  • 原文地址:https://www.cnblogs.com/rever/p/11251245.html
Copyright © 2011-2022 走看看