给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
例如:
给定二叉树 [3,9,20,null,null,15,7],
3 / 9 20 / 15 7
返回锯齿形层次遍历如下:
[ [3], [20,9], [15,7] ]
class Solution {
public:
vector<vector<int> > zigzagLevelOrder(TreeNode* root)
{
vector<vector<int> > res;
if(root == NULL)
return res;
queue<TreeNode*> q;
q.push(root);
int cnt = 0;
while(!q.empty())
{
int size = q.size();
vector<int> temp;
for(int i = 0; i < size; i++)
{
TreeNode *node = q.front();
q.pop();
temp.push_back(node ->val);
if(node ->left)
q.push(node ->left);
if(node ->right)
q.push(node ->right);
}
if((cnt & 1) == 1)
{
reverse(temp.begin(), temp.end());
}
res.push_back(temp);
cnt++;
}
return res;
}
};