# 二叉树的锯齿形层次遍历

3


/ \

9 20

 /  \


15 7

3 20 9 15 7

#include <iostream>
#include <queue>
#include <cstdlib>
#include <cstring>
#include<algorithm>
using namespace std;
struct TreeNode{
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(NULL), right(NULL) {}
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

TreeNode* inputTree(){
int n,count=0;
char item[100];
cin>>n;
if (n==0)
return NULL;
cin>>item;
TreeNode* root = new TreeNode(atoi(item));
count++;
queue<TreeNode*> nodeQueue;
nodeQueue.push(root);
while (count<n){
TreeNode* node = nodeQueue.front();
nodeQueue.pop();
cin>>item;
count++;
if (strcmp(item,"null")!=0){
int leftNumber = atoi(item);
node->left = new TreeNode(leftNumber);
nodeQueue.push(node->left);
}
if (count==n)
break;
cin>>item;
count++;
if (strcmp(item,"null")!=0){
int rightNumber = atoi(item);
node->right = new TreeNode(rightNumber);
nodeQueue.push(node->right);
}
}
return root;
}
int main(){
TreeNode* root;
root=inputTree();
vector<vector<int> > res=zigzagLevelOrder(root);
for(int i=0; i<res.size(); i++){
vector<int> v=res[i];
for(int j=0; j<v.size(); j++)
cout<<v[j]<<" ";
}
}


7
3 9 20 null null 15 7

3 20 9 15 7

vector<vector<int>> zigzagLevelOrder(TreeNode* root){
vector<vector<int>> res(100);
queue<pair<TreeNode*,int>> q;
if(root){
q.push(make_pair(root,0));
}
while(!q.empty()){
TreeNode* node=q.front().first;
int depth=q.front().second;
q.pop();
res[depth].push_back(node->val);
if(node->left){
q.push(make_pair(node->left,depth+1));
}
if(node->right){
q.push(make_pair(node->right,depth+1));
}
}
for(int i=0;i<res.size();i++){
if(i%2==1){
reverse(res[i].begin(),res[i].end());
}
}
return res;
}

04-27 2548
05-22 2364

10-13 1979
07-30 543
05-14 57
08-29 350
12-21 123
04-23 154