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 };
  • 相关阅读:
    Leangoo:用敏捷开发管理思维做团队协作的SaaS软件
    张江男的逆袭,我如何使用leangoo提升团队效率
    探索leangoo常用快捷键
    Tkinter教程之Event篇(3)
    Tkinter教程之Event篇(2)
    Tkinter教程之Event篇(1)'
    Tkinter教程之Grid篇
    Tkinter教程之Pack篇
    Tkinter教程之Canvas篇(4)
    Tkinter教程之Canvas篇(3)
  • 原文地址:https://www.cnblogs.com/habibah-chang/p/14486343.html
Copyright © 2011-2022 走看看