zoukankan      html  css  js  c++  java
  • 429. N-ary Tree Level Order Traversal

    问题:

    给定N叉树,将各个节点的值,按【层】构成数组输出。

    Example 1:
    Input: root = [1,null,3,2,4,null,5,6]
    Output: [[1],[3,2,4],[5,6]]
    
    Example 2:
    Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
    Output: [[1],[2,3,4,5],[6,7,8,9,10],[11,12,13],[14]]
     
    Constraints:
    The height of the n-ary tree is less than or equal to 1000
    The total number of nodes is between [0, 104]
    

      

    example 1:

    example 2:

    解法:BFS

    遍历树,对当前节点,将其children节点加入queue。

    遍历每层queue,按层加入group

    再将group存入res。

    代码参考:

     1 /*
     2 // Definition for a Node.
     3 class Node {
     4 public:
     5     int val;
     6     vector<Node*> children;
     7 
     8     Node() {}
     9 
    10     Node(int _val) {
    11         val = _val;
    12     }
    13 
    14     Node(int _val, vector<Node*> _children) {
    15         val = _val;
    16         children = _children;
    17     }
    18 };
    19 */
    20 
    21 class Solution {
    22 public:
    23     vector<vector<int>> levelOrder(Node* root) {
    24         vector<vector<int>> res;
    25         queue<Node*>q;
    26         if(root) q.push(root);
    27         while(!q.empty()) {
    28             int sz=q.size();
    29             vector<int> group;
    30             for(int i=0; i<sz; i++) {
    31                 Node* cur = q.front();
    32                 group.push_back(cur->val);
    33                 q.pop();
    34                 for(Node*p:cur->children) {
    35                     if(p){
    36                         q.push(p);
    37                     }
    38                 }
    39             }
    40             res.push_back(group);
    41         }
    42         return res;
    43     }
    44 };
  • 相关阅读:
    Java解析XML(一)、SAX
    Java注解
    NTKO OFFICE文档控件为何不能自动装载?
    Java解析XML(二)、DOM
    JAVA反射机制
    如何手工卸载和安装NTKO OFFICE文档控件
    使用内省的方式操作JavaBean
    JDK自带的native2ascii转码工具使用详解
    HTTP协议详解
    跳过编译器,获取泛型参数的实际类型
  • 原文地址:https://www.cnblogs.com/habibah-chang/p/14486343.html
Copyright © 2011-2022 走看看