forked from Amitshu2003/All-Codes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreverse_binary_tree.cpp
More file actions
53 lines (52 loc) · 1.37 KB
/
reverse_binary_tree.cpp
File metadata and controls
53 lines (52 loc) · 1.37 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
/**
* Definition for a binary tree node.
* 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) {}
* };
*/
class Solution {
public:
TreeNode* reverseOddLevels(TreeNode* root)
{
if(!root)
return root;
queue<TreeNode*> q;
q.push(root);
bool level = false;
while(q.size())
{
int qSize = q.size();
vector<int> vals;
vector<TreeNode*> refs;
while(qSize--)
{
TreeNode *top = q.front();
q.pop();
if(level)
{
vals.push_back(top->val);
refs.push_back(top);
}
if(top->left)
q.push(top->left);
if(top->right)
q.push(top->right);
}
if(level)
{
int n = vals.size();
for(int i = 0, j = n-1; i < n; i++, j--)
{
refs[i]->val = vals[j];
}
}
level = !level;
}
return root;
}
};