559. Maximum Depth of N-ary Tree

问题:

给定N叉树,求该树的最大深度。

Example 1:
Input: root = [1,null,3,2,4,null,5,6]
Output: 3

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: 5
 
Constraints:
The depth 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

将root节点入队,

每次遍历当前节点的所有children节点,入队,

遍历queue的层数,即为所求。

 

代码参考:

 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     int maxDepth(Node* root) {
24         int res = 0;
25         queue<Node*> q;
26         if(root) q.push(root);
27         while(!q.empty()) {
28             int sz = q.size();
29             for(int i=0; i<sz; i++) {
30                 Node* cur = q.front();
31                 q.pop();
32                 for(Node* c:cur->children) {
33                     if(c) q.push(c);
34                 }
35             }
36             res++;
37         }
38         return res;
39     }
40 };

 

posted @ 2021-03-10 16:46  habibah_chang  阅读(55)  评论(0编辑  收藏  举报