Skip to content

Commit 248428c

Browse files
committed
Merge pull request haoel#72 from xusiwei/master
new solution of "Binary Tree Level Order Traversal"
2 parents e6917d7 + 033ffe8 commit 248428c

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

algorithms/binaryTreeLevelOrderTraversal/binaryTreeLevelOrderTraversal.cpp

+33
Original file line numberDiff line numberDiff line change
@@ -65,12 +65,16 @@ struct TreeNode {
6565

6666
vector<vector<int> > levelOrder1(TreeNode *root);
6767
vector<vector<int> > levelOrder2(TreeNode *root);
68+
vector<vector<int> > levelOrder3(TreeNode *root);
6869

6970

7071
vector<vector<int> > levelOrder(TreeNode *root) {
7172
if (random()%2){
7273
return levelOrder1(root);
7374
}
75+
if (random()%2){
76+
return levelOrder3(root);
77+
}
7478
return levelOrder2(root);
7579
}
7680

@@ -149,6 +153,35 @@ vector<vector<int> > levelOrder2(TreeNode *root) {
149153
return vv;
150154
}
151155

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+
152185
void printTree(TreeNode *root)
153186
{
154187
if (root == NULL){

0 commit comments

Comments
 (0)