题意:中序序列+后序序列构建二叉树,之字形输出其层序序列。
思路:在结点的数据域中额外增加一个layer表示结点所在的层次,并定义vector<int> zigzag[maxn]存放最终结果。按照常规顺序进行层序遍历,将第i层的值存入到zigzag[i]中,最后输出时,第偶数层从左向右输出,第奇数层反之。
代码:
#include <cstdio> #include <queue> #include <vector> using namespace std; const int maxn=35; int in[maxn],post[maxn]; vector<int> zigzag[maxn]; int maxLayer=0; struct Node{ int val; int layer; Node *lchild,*rchild; Node(int v):val(v),layer(1),lchild(NULL),rchild(NULL){} }; Node* buildBiTree(int pL,int pR,int inL,int inR) { if(pL>pR) return NULL; int rootval=post[pR]; Node* root=new Node(rootval); int pos=inL; while(in[pos]!=rootval) pos++; int leftCnt=pos-inL; root->lchild=buildBiTree(pL,pL+leftCnt-1,inL,pos-1); root->rchild=buildBiTree(pL+leftCnt,pR-1,pos+1,inR); return root; } void levelOrderTraversal(Node* root) { queue<Node*> q; root->layer=1; q.push(root); while(!q.empty()){ Node* pNode=q.front(); q.pop(); if(pNode->layer > maxLayer) maxLayer=pNode->layer; zigzag[pNode->layer].push_back(pNode->val); if(pNode->lchild){ pNode->lchild->layer=pNode->layer+1; q.push(pNode->lchild); } if(pNode->rchild){ pNode->rchild->layer=pNode->layer+1; q.push(pNode->rchild); } } } int main() { //freopen("pat.txt","r",stdin); int n; scanf("%d",&n); for(int i=0;i<n;i++) scanf("%d",&in[i]); for(int i=0;i<n;i++) scanf("%d",&post[i]); Node* root=buildBiTree(0,n-1,0,n-1); levelOrderTraversal(root); printf("%d",root->val); for(int i=2;i<=maxLayer;i++){ if(i%2==0){ for(int j=0;j<zigzag[i].size();j++) printf(" %d",zigzag[i][j]); }else{ for(int j=zigzag[i].size()-1;j>=0;j--) printf(" %d",zigzag[i][j]); } } return 0; }
原文地址:https://www.cnblogs.com/kkmjy/p/9574417.html
时间: 2024-10-08 13:46:56