-
Notifications
You must be signed in to change notification settings - Fork 0
/
zigZagTraversalBT.cpp
46 lines (35 loc) · 1.09 KB
/
zigZagTraversalBT.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
class Solution{
public:
//Function to store the zig zag order traversal of tree in a list.
vector <int> zigZagTraversal(Node* root)
{
vector<int> result;
if(root == NULL)
return result;
queue<Node*> q;
q.push(root);
bool leftToRight = true;
while(!q.empty()) {
int size = q.size();
vector<int> ans(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;
ans[index] = frontNode -> data;
if(frontNode->left)
q.push(frontNode -> left);
if(frontNode->right)
q.push(frontNode -> right);
}
//direction change karni h
leftToRight = !leftToRight;
for(auto i: ans) {
result.push_back(i);
}
}
return result;
}
};