-
Notifications
You must be signed in to change notification settings - Fork 0
/
Problem_1302_DeepestLeavesSum.cc
96 lines (89 loc) · 1.75 KB
/
Problem_1302_DeepestLeavesSum.cc
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
#include <iostream>
#include "UnitTest.h"
using namespace std;
class TreeNode
{
public:
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) {}
};
class Info
{
public:
int deep;
int value;
Info()
{
deep = 0;
value = 0;
}
Info(int d, int v)
{
deep = d;
value = v;
}
};
class Solution
{
public:
Info process(TreeNode *cur)
{
if (cur == nullptr)
{
return Info(0, 0);
}
if (cur->left == nullptr && cur->right == nullptr)
{
return Info(1, cur->val);
}
Info l;
Info r;
if (cur->left != nullptr)
{
l = process(cur->left);
}
if (cur->right != nullptr)
{
r = process(cur->right);
}
int deep = std::max(l.deep, r.deep) + 1;
int value = 0;
if (l.deep == r.deep)
{
value = l.value + r.value;
}
else if (l.deep > r.deep)
{
value = l.value;
}
else
{
value = r.value;
}
return Info(deep, value);
}
int deepestLeavesSum(TreeNode *root) { return process(root).value; }
};
void testDeepestLeavesSum()
{
Solution s;
TreeNode *x8 = new TreeNode(8, nullptr, nullptr);
TreeNode *x7 = new TreeNode(7, nullptr, nullptr);
TreeNode *x6 = new TreeNode(6, nullptr, x8);
TreeNode *x5 = new TreeNode(5, nullptr, nullptr);
TreeNode *x4 = new TreeNode(4, x7, nullptr);
TreeNode *x3 = new TreeNode(3, nullptr, x6);
TreeNode *x2 = new TreeNode(2, x4, x5);
TreeNode *x1 = new TreeNode(1, x2, x3);
EXPECT_EQ_INT(s.deepestLeavesSum(x1), 15);
EXPECT_SUMMARY;
}
int main()
{
testDeepestLeavesSum();
return 0;
}