forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 1
/
count-nodes-equal-to-sum-of-descendants.cpp
59 lines (55 loc) · 1.66 KB
/
count-nodes-equal-to-sum-of-descendants.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
// Time: O(n)
// Space: O(h)
class Solution {
public:
int equalToDescendants(TreeNode* root) {
return iter_dfs(root);
}
private:
int iter_dfs(TreeNode *node) {
int result = 0;
uint64_t total = 0;
vector<tuple<int, TreeNode *, unique_ptr<uint64_t>, unique_ptr<uint64_t>, uint64_t*>> stk;
stk.emplace_back(1, node, nullptr, nullptr, &total);
while (!empty(stk)) {
const auto [step, node, ret1, ret2, ret] = move(stk.back()); stk.pop_back();
if (step == 1) {
if (!node) {
continue;
}
auto ret1 = make_unique<uint64_t>(), ret2 = make_unique<uint64_t>();
auto p1 = ret1.get(), p2 = ret2.get();
stk.emplace_back(2, node, move(ret1), move(ret2), ret);
stk.emplace_back(1, node->right, nullptr, nullptr, p2);
stk.emplace_back(1, node->left, nullptr, nullptr, p1);
} else if (step == 2) {
if (node->val == *ret1 + *ret2) {
++result;
}
*ret = *ret1 + *ret2 + node->val;
}
}
return result;
}
};
// Time: O(n)
// Space: O(h)
class Solution2 {
public:
int equalToDescendants(TreeNode* root) {
int result = 0;
dfs(root, &result);
return result;
}
private:
uint64_t dfs(TreeNode *node, int *result) {
if (!node) {
return 0;
}
uint64_t total = dfs(node->left, result) + dfs(node->right, result);
if (node->val == total) {
++(*result);
}
return total + node->val;
}
};