Skip to content

Commit dd80961

Browse files
authored
Create main.cpp
1 parent 9404101 commit dd80961

File tree

1 file changed

+42
-0
lines changed
  • 17 - Binary Tree Data Structure Problems/14 - Zigzag Tree Traversal

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
class Solution{
2+
public:
3+
//Function to store the zig zag order traversal of tree in a list.
4+
vector <int> zigZagTraversal(Node* root)
5+
{
6+
7+
vector<int> result;
8+
if(root == NULL) return result;
9+
10+
bool LTR = true;
11+
12+
queue<Node*> q;
13+
q.push(root);
14+
15+
while(!q.empty()){
16+
int size = q.size();
17+
vector<int> ans(size);
18+
19+
for(int i = 0; i < size; i++){
20+
Node* frontNode = q.front();
21+
q.pop();
22+
23+
int index = LTR ? i : size - i - 1;
24+
ans[index] = frontNode -> data;
25+
26+
if(frontNode -> left) q.push(frontNode -> left);
27+
if(frontNode -> right) q.push(frontNode -> right);
28+
29+
}
30+
31+
LTR = !LTR;
32+
33+
for(auto i : ans){
34+
result.push_back(i);
35+
}
36+
37+
}
38+
39+
return result;
40+
41+
}
42+
};

0 commit comments

Comments
 (0)