-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBinary tree zig zag fashion
56 lines (49 loc) · 1.23 KB
/
Binary tree zig zag fashion
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
/*Structure of the node of the binary tree is as
struct Node {
int data;
Node *left;
Node *right;
Node(int val) {
data = val;
left = right = NULL;
}
};
*/
class Solution{
public:
//Function to store the zig zag order traversal of tree in a list.
vector <int> zigZagTraversal(Node* root)
{
vector<int> res;
if(root == NULL){
return res;
}
queue<Node*> q;
q.push(root);
bool leftToRight = true;
while(!q.empty()){
int size = q.size();
vector<int> temp(size);
//level process
for(int i=0;i<size;i++){
Node* frontNode = q.front();
q.pop();
//normal insert or reverse insert
int index = leftToRight ? i : size-i-1;
temp[index] = frontNode->data;
if(frontNode->left){
q.push(frontNode->left);
}
if(frontNode->right){
q.push(frontNode->right);
}
}
//direction change
leftToRight = !leftToRight;
for(auto i: temp){
res.push_back(i);
}
}
return res;
}
};