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] ]
confused what "{1,#,2,3}" means? >
read more on how binary tree is serialized on OJ.
/*********************************
* 日期:2014-12-09
* 作者:SJF0115
* 题号: Binary Tree Zigzag Level Order Traversal
* 来源:https://oj.leetcode.com/problems/binary-tree-zigzag-level-order-traversal/
* 结果:AC
* 来源:LeetCode
* 总结:
**********************************/
#include <iostream>
#include <malloc.h>
#include <stack>
#include <vector>
#include <queue>
using namespace std;
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<int> level;
vector<vector<int> > levels;
if(root == NULL){
return levels;
}
queue<TreeNode*> curq,nextq;
stack<TreeNode*> curs,nexts;
// 第index层
int index = 1;
//入队列
curq.push(root);
// 层次遍历
while(!curq.empty() || !curs.empty()){
//当前层遍历
while(!curq.empty() || !curs.empty()){
TreeNode *p,*q;
// 第奇数层用队列存储
if(index & 1){
p = curq.front();
curq.pop();
// 第偶数层用栈存储下一层节点
//左子树
if(p->left){
nexts.push(p->left);
// 用于从左到右遍历节点
nextq.push(p->left);
}
//右子树
if(p->right){
nexts.push(p->right);
//用于从左到右遍历
nextq.push(p->right);
}
}
// 第偶数层用栈存储
else{
p = curs.top();
curs.pop();
// 存储节点时都是从左到右遍历
q = curq.front();
curq.pop();
// 第奇数层用队列存储下一层节点
//左子树
if(q->left){
nextq.push(q->left);
}
//右子树
if(q->right){
nextq.push(q->right);
}
}
level.push_back(p->val);
}
index++;
levels.push_back(level);
level.clear();
swap(nextq,curq);
swap(nexts,curs);
}//while
return levels;
}
};
//按先序序列创建二叉树
int CreateBTree(TreeNode* &T){
char data;
//按先序次序输入二叉树中结点的值(一个字符),‘#’表示空树
cin>>data;
if(data == '#'){
T = NULL;
}
else{
T = (TreeNode*)malloc(sizeof(TreeNode));
//生成根结点
T->val = data-'0';
//构造左子树
CreateBTree(T->left);
//构造右子树
CreateBTree(T->right);
}
return 0;
}
int main() {
Solution solution;
TreeNode* root(0);
CreateBTree(root);
vector<vector<int> > vecs = solution.zigzagLevelOrder(root);
for(int i = 0;i < vecs.size();i++){
for(int j = 0;j < vecs[i].size();j++){
cout<<vecs[i][j];
}
cout<<endl;
}
}
[LeetCode]Binary Tree Zigzag Level Order Traversal
原文地址:http://blog.csdn.net/sunnyyoona/article/details/41821951