-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinary Tree Zigzag Level Order Traversal__BFS.cpp
127 lines (111 loc) · 2.49 KB
/
Binary Tree Zigzag Level Order Traversal__BFS.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
/*
Binary Tree Zigzag Level Order Traversal
Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
For example:
Given binary tree {3,9,20,#,#,15,7},
3
/ \
9 20
/ \
15 7
return its zigzag level order traversal as:
[
[3],
[20,9],
[15,7]
]
*/
#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include<stack>
using namespace std;
//Definition for binary tree
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
vector<vector<int> > zigzagLevelOrder(TreeNode *root) {
vector<vector<int>>result;
vector<stack<int>>rec;
std::queue<pair<TreeNode*,int>> visited, unvisited;
if (root == NULL)
return result;
unvisited.push(make_pair(root,0));
//vector<int>temp;
//temp.push_back(root->val);
//result.push_back(temp);
while (!unvisited.empty()){
vector<int>temp;
pair<TreeNode*,int> current = unvisited.front();
int level = current.second;
if (rec.size() <= level)
rec.push_back(stack<int>());
rec[level].push(current.first->val);
if (current.first->left != NULL){
unvisited.push(make_pair(current.first->left,current.second+1));
}
if (current.first->right != NULL){
unvisited.push(make_pair(current.first->right,current.second+1));
}
visited.push(current);
unvisited.pop();
}
for (int i = 0; i < rec.size(); i++){
vector<int>temp;
vector<int>temp_re;
while (!rec[i].empty()){
temp.push_back(rec[i].top());
rec[i].pop();
}
if (i % 2 == 0){
vector<int>temp_re(temp);
int len = temp.size();
for (int j = 0; j < len; j++){
temp_re[j] = temp[len - j-1];
}
result.push_back(temp_re);
temp_re.clear();
temp.clear();
}
else{
result.push_back(temp);
temp.clear();
}
}
return result;
}
};
void main()
{
Solution mySolu;
TreeNode Root(1);
TreeNode temp0(2);
TreeNode temp1(3);
TreeNode temp2(4);
TreeNode temp3(5);
TreeNode temp4(6);
TreeNode temp5(7);
TreeNode temp6(8);
TreeNode temp7(9);
//Root.left = &temp0;
//Root.right = &temp1;
vector<vector<int>> res;
//vector<int>temp{ 1, 2, 3 };
//temp[3] = 5;
//res.push_back(temp);
//res.push_back(temp);
//res.push_back(temp);
res = mySolu.zigzagLevelOrder(&Root);
for (int i = 0; i < res.size(); i++){
for (int j = 0; j < res[i].size(); j++){
cout << res[i][j] << " ";
}
cout << endl;
}
}