-
Notifications
You must be signed in to change notification settings - Fork 107
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added solution for diameter of n ary tree.
- Loading branch information
1 parent
a3fac8b
commit 2b0c32f
Showing
1 changed file
with
42 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
/* | ||
// 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; | ||
} | ||
}; | ||
*/ | ||
|
||
class Solution { | ||
public: | ||
int diameter(Node* root) { | ||
int res = 0; // tc: O(n), sc: O(n) | ||
dfs(root, res); | ||
return res; | ||
} | ||
int dfs(Node* root, int& res) { | ||
if(!root) return 0; | ||
int first = 0, second = 0; | ||
for(auto& child:root->children) { | ||
int tmp = dfs(child, res); | ||
if(tmp >= first) { | ||
second = first; | ||
first = tmp; | ||
} | ||
else if(tmp >= second) second = tmp; | ||
} | ||
res = max(res, first + second); | ||
return max(first, second) + 1; | ||
} | ||
}; |