forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
number-of-good-leaf-nodes-pairs.cpp
100 lines (94 loc) · 3.17 KB
/
number-of-good-leaf-nodes-pairs.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
// Time: O(n)
// Space: O(h)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
// Time: O(n)
// Space: O(h)
class Solution {
public:
int countPairs(TreeNode* root, int distance) {
return iter_dfs(distance, root);
}
private:
int iter_dfs(int distance, TreeNode *root) {
using RET = unordered_map<int, int>;
int result = 0;
RET ret;
vector<tuple<int, TreeNode *, shared_ptr<RET>, shared_ptr<RET>, RET *>> stk = {{1, root, nullptr, nullptr, &ret}};
while (!stk.empty()) {
const auto [step, node, left, right, ret] = stk.back(); stk.pop_back();
if (step == 1) {
if (!node) {
continue;
}
if (!node->left && !node->right) {
(*ret)[0] = 1;
continue;
}
const auto& left = make_shared<RET>(), &right = make_shared<RET>();
stk.emplace_back(2, nullptr, left, right, ret);
stk.emplace_back(1, node->right, nullptr, nullptr, right.get());
stk.emplace_back(1, node->left, nullptr, nullptr, left.get());
} else {
for (const auto& [left_d, left_c] : *left) {
for (const auto& [right_d, right_c] : *right) {
if (left_d + right_d + 2 <= distance) {
result += left_c * right_c;
}
}
}
for (const auto& [left_d, left_c] : *left) {
(*ret)[left_d + 1] += left_c;
}
for (const auto& [right_d, right_c] : *right) {
(*ret)[right_d + 1] += right_c;
}
}
}
return result;
}
};
// Time: O(n)
// Space: O(h)
class Solution2 {
public:
int countPairs(TreeNode* root, int distance) {
return dfs(distance, root).first;
}
private:
pair<int, unordered_map<int, int>> dfs(int distance, TreeNode *node) {
if (!node) {
return {0, {}};
}
if (!node->left && !node->right) {
return {0, {{0, 1}}};
}
const auto& left = dfs(distance, node->left);
const auto& right = dfs(distance, node->right);
int result = left.first + right.first;
for (const auto& [left_d, left_c] : left.second) {
for (const auto& [right_d, right_c] : right.second) {
if (left_d + right_d + 2 <= distance) {
result += left_c * right_c;
}
}
}
unordered_map<int, int> count;
for (const auto& [left_d, left_c] : left.second) {
count[left_d + 1] += left_c;
}
for (const auto& [right_d, right_c] : right.second) {
count[right_d + 1] += right_c;
}
return {result, count};
}
};