还是开始没想清楚,发现用2个stack要清楚很多,2个vector就搞晕了。
Sigh,贴一个终于通过的明天再看再简化。每次碰到这种开始以为简单又老是写不对的
题就很有挫折感!
vector > zigzagLevelOrder(TreeNode *root) {
vector> ret;
vector levelVals;
stack curLevel;
stack nextLevel;
if (root==NULL)
return ret;
TreeNode *r = root;
curLevel.push(r);
bool l2r = true;
while(!curLevel.empty())
{
if (!l2r)
{
while(!curLevel.empty())
{
TreeNode *tmp = curLevel.top();
levelVals.push_back(tmp->val);
if (tmp->left!=NULL)
nextLevel.push(tmp->left);
if (tmp->right!=NULL)
nextLevel.push(tmp->right);
curLevel.pop();
}
l2r=true;
}
else
{
while(!curLevel.empty())
{
TreeNode *tmp = curLevel.top();
levelVals.push_back(tmp->val);
if (tmp->right!=NULL)
nextLevel.push(tmp->right);
if (tmp->left!=NULL)
nextLevel.push(tmp->left);
curLevel.pop();
}
l2r=false;
}
reverse(levelVals.begin(),levelVals.end());
ret.push_back(levelVals);
swap(curLevel, nextLevel);
levelVals.clear();
}
return ret;
}