forked from larissalages/code_problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path559.cpp
More file actions
52 lines (43 loc) · 1.19 KB
/
559.cpp
File metadata and controls
52 lines (43 loc) · 1.19 KB
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
//LINK TO THE PROBLEM :- https://leetcode.com/problems/maximum-depth-of-n-ary-tree/
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;
Node() {}
Node(int _val) {
val = _val;
}
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/
/*EXPLANATION :- We will be using here simple DFS the only difference being that there is no visited array as we have in case of graphs normally. The height() func takes two parameters root of the N-ary tree and initial height which is passed as 0 and the height increases as we mive further down the tree for every leaf node we calculate the max. depth so far for all the leaves*/
class Solution {
public:
int ans=0;
void height(Node*root,int ht)
{
if(root)
{
ht++;
for(int i=0; i<root->children.size(); i++)
{
height(root->children[i],ht);
}
ans=max(ans,ht);
}
}
int maxDepth(Node* root)
{
if(root)
{
height(root,0);
return ans;
}
return 0;
}
};