forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
diameter-of-n-ary-tree.cpp
50 lines (46 loc) · 1.5 KB
/
diameter-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
// Time: O(n)
// Space: O(h)
class Solution {
public:
int diameter(Node* root) {
return iter_dfs(root).first;
}
private:
pair<int, int> iter_dfs(Node *root) {
using RET = pair<int, int>;
RET result;
vector<tuple<int, Node *, shared_ptr<RET>, RET *>> stk = {{1, root, nullptr, &result}};
while (!stk.empty()) {
const auto [step, node, ret2, ret] = stk.back(); stk.pop_back();
if (step == 1) {
for (int i = node->children.size() - 1; i >= 0; --i) {
const auto& ret2 = make_shared<RET>();
stk.emplace_back(2, nullptr, ret2, ret);
stk.emplace_back(1, node->children[i], nullptr, ret2.get());
}
} else {
ret->first = max(ret->first, max(ret2->first, ret->second + ret2->second + 1));
ret->second = max(ret->second, ret2->second + 1);
}
}
return result;
}
};
// Time: O(n)
// Space: O(h)
class Solution2 {
public:
int diameter(Node* root) {
return dfs(root).first;
}
private:
pair<int, int> dfs(Node *node) {
int max_dia = 0, max_depth = 0;
for (const auto& child : node->children) {
const auto& [child_max_dia, child_max_depth] = dfs(child);
max_dia = max({max_dia, child_max_dia, max_depth + child_max_depth + 1});
max_depth = max(max_depth, child_max_depth + 1);
}
return {max_dia, max_depth};
}
};