Binary Tree Zigzag Level Order Traversal
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,#,#,15,7},3 / \ 9 20 / \ 15 7
return its zigzag level order traversal as:
[ [3], [20,9], [15,7] ]
解析
如果输出下边这样的结果,是不是想到这道题Binary Tree Level Order Traversal
[
[3],
[9,20],
[15,7]
]
如果有了上边的结果,只需要对特定的行进行逆转即可。
代码
/**
* 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>> vvi;
if(root==NULL) return vvi;
queue<TreeNode*> que;
TreeNode* p=root;
que.push(p);
int curcount=1;//当前层结点数
int nextcount=0;//下一层结点数
int depth=0;//树的深度,从0开始计算
vector<int> vi;
while(!que.empty()){
p=que.front();
que.pop();
vi.push_back(p->val);
--curcount;
if(p->left){
++nextcount;
que.push(p->left);
}
if(p->right){
++nextcount;
que.push(p->right);
}
if(curcount==0){//当前层最后一个结点,下次循环进入下一层
if(depth&1){
reverse(vi.begin(),vi.end());
}
vvi.push_back(vi);
vi.clear();
curcount=nextcount;
nextcount=0;
++depth;
}
}
return vvi;
}
};
ps: 这段代码用了很多次了,屡试不爽。需要掌握~~~~