Skip to content

Commit

Permalink
Added solution for diameter of n ary tree.
Browse files Browse the repository at this point in the history
  • Loading branch information
Xtha-Sunil committed Oct 30, 2024
1 parent a3fac8b commit 2b0c32f
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions C++/diameter-of-n-ary-tree.cpp
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;
}
};

0 comments on commit 2b0c32f

Please sign in to comment.