标签:
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).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ 9 20
/ 15 7
return its zigzag level order traversal as:
[ [3], [20,9], [15,7] ]
求Z型遍历
BFS后,对偶数行进行翻转
/**
* Definition for a binary tree node.
* 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>> res;
if(root==NULL)return res;
vector<int> v;
queue<TreeNode*> q;
q.push(root);
int curCount=1;
int nextCount=0;
while(!q.empty())
{
TreeNode* curNode=q.front();
v.push_back(curNode->val);
q.pop();
curCount--;
if(curNode->left)
{
q.push(curNode->left);
nextCount++;
}
if(curNode->right)
{
q.push(curNode->right);
nextCount++;
}
if(curCount==0)
{
curCount=nextCount;
nextCount=0;
res.push_back(v);
v.clear();
}
}
for(int i=1;i<res.size();i+=2)
reverse(res[i].begin(),res[i].end());
return res;
}
};leetcode No103. Binary Tree Zigzag Level Order Traversal
标签:
原文地址:http://blog.csdn.net/u011391629/article/details/52253719