-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinaryTreeTilt.cpp
82 lines (82 loc) · 2.07 KB
/
BinaryTreeTilt.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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int helper(TreeNode * root){
int left_sum = 0;
int right_sum = 0;
if(root==NULL){
return 0;
}
TreeNode * curr_left = root->left;
queue<TreeNode*> q;
if(root->left){
q.push(curr_left);
}
while(!q.empty()){
int x = q.size();
for(int i = 0;i<x;i++){
TreeNode * t = q.front();
left_sum += t->val;
if(t->left){
q.push(t->left);
}
if(t->right){
q.push(t->right);
}
q.pop();
}
}
TreeNode * curr = root->right;
if(root->right){
q.push(root->right);
}
while(!q.empty()){
int x = q.size();
for(int i = 0;i<x;i++){
TreeNode * t = q.front();
right_sum += t->val;
if(t->left){
q.push(t->left);
}
if(t->right){
q.push(t->right);
}
q.pop();
}
}
return abs(left_sum - right_sum);
}
bool isLeaf(TreeNode * root){
return !root->left && !root->right;
}
int findTilt(TreeNode* root) {
vector<int> tilt;
queue<TreeNode * > q;
if(root){
q.push(root);
}
while(!q.empty()){
int x= q.size();
for(int i = 0;i<x;i++){
TreeNode * t = q.front();
tilt.push_back(helper(t));
if(t->left){
q.push(t->left);
}
if(t->right){
q.push(t->right);
}
q.pop();
}
}
return accumulate(tilt.begin(), tilt.end(), 0);
}
};