-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path559.maximum-depth-of-n-ary-tree.cpp
72 lines (69 loc) · 1.49 KB
/
559.maximum-depth-of-n-ary-tree.cpp
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/*
* @lc app=leetcode id=559 lang=cpp
*
* [559] Maximum Depth of N-ary Tree
*
* https://leetcode.com/problems/maximum-depth-of-n-ary-tree/description/
*
* algorithms
* Easy (64.10%)
* Total Accepted: 41.4K
* Total Submissions: 63.5K
* Testcase Example: '{"$id":"1","children":[{"$id":"2","children":[{"$id":"5","children":[],"val":5},{"$id":"6","children":[],"val":6}],"val":3},{"$id":"3","children":[],"val":2},{"$id":"4","children":[],"val":4}],"val":1}'
*
* 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.
*
* For example, given a 3-ary tree:
*
*
*
*
*
*
* We should return its max depth, which is 3.
*
*
*
* Note:
*
*
* The depth of the tree is at most 1000.
* The total number of nodes is at most 5000.
*
*
*/
/*
// 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 {
public:
int MAXX;
void traverse(Node* root, int h){
if(root->children.size() == 0){
MAXX = max(MAXX, h);
return ;
}
for(auto child: root->children)
traverse(child, h+1);
}
int maxDepth(Node* root) {
MAXX = 0;
if(root == NULL)
return MAXX;
traverse(root, 1);
return MAXX;
}
};