0%

maximum-depth-of-n-ary-tree

Maximum Depth of N-ary Tree – LeetCode 559

Problem

Description

Given a n-ary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Answer

Original

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;

Node() {}

Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {X
public:
int maxDepth(Node* root) {
if(root){
int Max = 0;
for(auto const &i : root->children)
Max = max(Max, maxDepth(i));
return Max + 1;
} else
return 0;
}
};

思路

简单的数的DFS遍历。时间复杂度$O(n)$,空间复杂度$O(n)$。
耗时$40$ ms,排名$11.47\%$

Better

思路

还没看到更好的思路。