File tree 1 file changed +33
-0
lines changed
algorithms/binaryTreeLevelOrderTraversal
1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change @@ -65,12 +65,16 @@ struct TreeNode {
65
65
66
66
vector<vector<int > > levelOrder1 (TreeNode *root);
67
67
vector<vector<int > > levelOrder2 (TreeNode *root);
68
+ vector<vector<int > > levelOrder3 (TreeNode *root);
68
69
69
70
70
71
vector<vector<int > > levelOrder (TreeNode *root) {
71
72
if (random ()%2 ){
72
73
return levelOrder1 (root);
73
74
}
75
+ if (random ()%2 ){
76
+ return levelOrder3 (root);
77
+ }
74
78
return levelOrder2 (root);
75
79
}
76
80
@@ -149,6 +153,35 @@ vector<vector<int> > levelOrder2(TreeNode *root) {
149
153
return vv;
150
154
}
151
155
156
+ vector<vector<int > > levelOrder3 (TreeNode *root) {
157
+ vector< vector<int > > vv;
158
+ if (root == NULL ) return vv;
159
+
160
+ int level = 0 ; // current level.
161
+ TreeNode *last = root; // last node of currrent level.
162
+ queue<TreeNode*> q;
163
+
164
+ q.push (root);
165
+ vv.push_back (vector<int >());
166
+ while (!q.empty ()) {
167
+ TreeNode *p = q.front ();
168
+ q.pop ();
169
+
170
+ vv[level].push_back (p->val );
171
+ if (p->left ) q.push (p->left );
172
+ if (p->right ) q.push (p->right );
173
+
174
+ if (p == last) {
175
+ level++;
176
+ last = q.back ();
177
+ vv.push_back (vector<int >()); // new buffer for next row.
178
+ }
179
+ }
180
+ vv.pop_back ();
181
+
182
+ return vv;
183
+ }
184
+
152
185
void printTree (TreeNode *root)
153
186
{
154
187
if (root == NULL ){
You can’t perform that action at this time.
0 commit comments