File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed
17 - Binary Tree Data Structure Problems/14 - Zigzag Tree Traversal Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change 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+ };
You can’t perform that action at this time.
0 commit comments