Skip to content

Commit dd0da77

Browse files
authored
Merge pull request #241 from rishab1128/master
Added 559.Maximum Depth of N-ary Tree using DFS
2 parents 225ed0e + 58a795b commit dd0da77

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

leetcode/cpp/Tree/559.cpp

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
//LINK TO THE PROBLEM :- https://leetcode.com/problems/maximum-depth-of-n-ary-tree/
2+
/*
3+
// Definition for a Node.
4+
class Node {
5+
public:
6+
int val;
7+
vector<Node*> children;
8+
9+
Node() {}
10+
11+
Node(int _val) {
12+
val = _val;
13+
}
14+
15+
Node(int _val, vector<Node*> _children) {
16+
val = _val;
17+
children = _children;
18+
}
19+
};
20+
*/
21+
22+
/*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*/
23+
24+
class Solution {
25+
public:
26+
27+
int ans=0;
28+
void height(Node*root,int ht)
29+
{
30+
if(root)
31+
{
32+
ht++;
33+
for(int i=0; i<root->children.size(); i++)
34+
{
35+
height(root->children[i],ht);
36+
}
37+
38+
ans=max(ans,ht);
39+
40+
}
41+
}
42+
43+
int maxDepth(Node* root)
44+
{
45+
if(root)
46+
{
47+
height(root,0);
48+
return ans;
49+
}
50+
return 0;
51+
}
52+
};

0 commit comments

Comments
 (0)