原题
思路
与102题层次遍历最大的区别就是,此题要求先在开始层从左到右遍历,下一层再从右到左,再从左到右。。。依次类推,所以只要在层次遍历的代码中,加上一个计数变量level记录当前层,初始值为1,当下一个数是下一层时,判断level%2是否等于0,如果level为奇数则从左到右,如果为偶数,则将存储在vector中的这一层数进行逆转,然后存储到最后的结果向量中。
code
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int>> result;
queue<TreeNode *> q;
if (!root)
{
return result;
}
q.push(root);
q.push(NULL);
vector<int> cur;
int level = 1;
while (!q.empty())
{
TreeNode* t = q.front();
q.pop();
if (t == NULL)
{
if (level % 2 == 0)
{
reverse(cur.begin(), cur.end());
}
result.push_back(cur);
cur.resize(0);
if (q.size() > 0)
{
q.push(NULL);
}
level++;
}
else
{
cur.push_back(t->val);
if (t->left)
{
q.push(t->left);
}
if (t->right)
{
q.push(t->right);
}
}
}
return result;
}
};