-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDifferenceOddEvenLevel.cpp
More file actions
53 lines (53 loc) · 1.44 KB
/
DifferenceOddEvenLevel.cpp
File metadata and controls
53 lines (53 loc) · 1.44 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
#include<vector>
#include<queue>
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
int solve(TreeNode* A){
//maintain track at every level
//firstLevel is odd
bool oddLevel = true;
int oddLevelSum = 0,evenLevelSum = 0;
std::queue<TreeNode*> q;
q.push(A);
while(!q.empty()){
if(oddLevel){
int currLevelSize = q.size();
int index = 0;
while(index<currLevelSize){
TreeNode* currNode = q.front();
q.pop();
oddLevelSum+=currNode->val;
if(currNode->left){
q.push(currNode->left);
}
if(currNode->right){
q.push(currNode->right);
}
++index;
}
oddLevel = false;
}
else{
int currLevelSize = q.size();
int index = 0;
while(index<currLevelSize){
TreeNode* currNode = q.front();
q.pop();
evenLevelSum+=currNode->val;
if(currNode->left){
q.push(currNode->left);
}
if(currNode->right){
q.push(currNode->right);
}
++index;
}
oddLevel = true;
}
}
return oddLevelSum-evenLevelSum;
}