-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_tree_tilt.cpp
More file actions
83 lines (76 loc) · 2.19 KB
/
binary_tree_tilt.cpp
File metadata and controls
83 lines (76 loc) · 2.19 KB
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
/*
* =====================================================================================
*
* Filename: binary_tree_tilt.cpp
*
* Description: 563. Binary Tree Tilt.
* https://leetcode.com/problems/binary-tree-tilt/
*
* Version: 1.0
* Created: 02/25/23 10:25:07
* Revision: none
* Compiler: gcc
*
* Author: xianfeng.zhu@gmail.com
* Organization:
*
* =====================================================================================
*/
#include <utility>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
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) {}
static TreeNode *convert(const std::vector<int *> &nums, const int i = 0) {
if (i >= nums.size() || nums[i] == nullptr) {
return nullptr;
}
TreeNode *root = new TreeNode(*nums[i]);
root->left = convert(nums, 2 * i + 1);
root->right = convert(nums, 2 * i + 2);
return root;
}
};
// Depth first search
class Solution {
public:
int findTilt(TreeNode *root) {
int tilt = 0;
dfsSum(root, tilt);
return tilt;
}
int dfsSum(TreeNode *root, int &tilt) {
if (root == nullptr) {
return 0;
}
const int a = dfsSum(root->left, tilt);
const int b = dfsSum(root->right, tilt);
tilt += std::abs(a - b);
return (root->val + a + b);
}
};
TEST(Solution, findTilt) {
#define _N(x) new int(x)
std::vector<std::pair<TreeNode *, int>> cases = {
std::make_pair(TreeNode::convert(std::vector<int *>{_N(1), _N(2), _N(3)}),
1),
std::make_pair(TreeNode::convert(std::vector<int *>{
_N(4), _N(2), _N(9), _N(3), _N(5), nullptr, _N(7)}),
15),
std::make_pair(
TreeNode::convert(std::vector<int *>{
_N(21), _N(7), _N(14), _N(1), _N(1), _N(2), _N(2), _N(3), _N(3)}),
9),
};
for (auto &c : cases) {
EXPECT_EQ(Solution().findTilt(c.first), c.second);
}
#undef _N
}