vector<vector<int> > levelOrder(TreeNode *root) {
vector<vector<int> > ret;
if (!root) return ret;
TreeNode*pointer=root;
queue<TreeNode*> aQueue;
aQueue.push(pointer);
vector<int> temp;
int curlevel=1,nextlevel=0;
while(!aQueue.empty())
{
curlevel--;
pointer=aQueue.front();
aQueue.pop();
temp.push_back(pointer->val);
if (pointer->left)
{aQueue.push(pointer->left); nextlevel++;}
if (pointer->right)
{aQueue.push(pointer->right); nextlevel++;}
if (curlevel==0)
{
ret.push_back(temp);
temp.clear();
curlevel=nextlevel;
nextlevel=0;
}
}
return ret;
}
//another flavor, using NULL mark, by anniekim
vector<vector<int> > levelOrder(TreeNode *root) {
vector<vector<int> > res;
if (!root) return res;
queue<TreeNode *> q;
q.push(root);
q.push(NULL);
vector<int> level;
while (true)
{
TreeNode *node = q.front(); q.pop();
if (!node)
{
res.push_back(level);
level.clear();
if (q.empty()) break; // end
q.push(NULL);
}
else
{
level.push_back(node->val);
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
}
}
return res;
}
//another flavor
vector<vector<int> > levelOrder(TreeNode *root) {
if (!root) return vector<vector<int> >();
TreeNode*pointer=root;
queue<TreeNode*> currentLevel, nextLevel;
currentLevel.push(pointer);
vector<vector<int> > ret;
while(!currentLevel.empty()||!nextLevel.empty())
{
vector<int> temp1,temp2;
while(!currentLevel.empty())
{
pointer=currentLevel.front();
currentLevel.pop();
temp1.push_back(pointer->val);
if (pointer->left)
nextLevel.push(pointer->left);
if (pointer->right)
nextLevel.push(pointer->right);
}
while(!nextLevel.empty())
{
pointer=nextLevel.front();
nextLevel.pop();
temp2.push_back(pointer->val);
if (pointer->left)
currentLevel.push(pointer->left);
if (pointer->right)
currentLevel.push(pointer->right);
}
ret.push_back(temp1);
if(temp2.size()>0)
ret.push_back(temp2);
}
return ret;
}
No comments:
Post a Comment