题目:Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
思路:层序遍历的一个小小的变种。偶数层把顺序逆置。
代码:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int> > zigzagLevelOrder(TreeNode *root) {
vector<vector<int> > result;
if(root == NULL)
return result;
vector<int> level;
queue<TreeNode *> q;
q.push(root);
q.push(NULL);
int i = 0;
while(!q.empty())
{
TreeNode *p = q.front();
q.pop();
if(p == NULL)
{
if(i&1 == 1)
reverse(level.begin(), level.end());
i++;
result.push_back(level);
level.clear();
if(!q.empty())
q.push(NULL);
}
else
{
level.push_back(p->val);
if(p->left != NULL)
q.push(p->left);
if(p->right != NULL)
q.push(p->right);
}
}
return result;
}
};