标签:node 0ms pac 第一个 建二叉树 amp tree 字符 stdio.h
2 abdegcf dbgeafc xnliu lnixu
dgebfca abcdefg linux xnuli
#include <stdio.h> #include <iostream> #include <cstring> #include <queue> #include <algorithm> using namespace std; typedef struct node { char data; node *lch,*rch; }btree,*bt; char pre[55],ins[55]; void build(bt &T,char *pre,char *ins,int n) //依据先序和中序重建二叉树 { if(n<=0) T=NULL; else { int k=strchr(ins,pre[0])-ins; T=new btree; T->data=pre[0]; build(T->lch,pre+1,ins,k); build(T->rch,pre+k+1,ins+k+1,n-k-1); } } void last(bt T)//后序遍历 { if(T) { last(T->lch); last(T->rch); cout<<T->data; } } void level(bt T) //层次遍历(BFS) { queue <btree> Q; Q.push(*T); while(!Q.empty()) { btree next=Q.front(); Q.pop(); cout<<next.data; if(next.lch) Q.push(*(next.lch)); if(next.rch) Q.push(*(next.rch)); } } int main() { bt root; int n; cin>>n; getchar(); while(n--) { cin>>pre>>ins; build(root,pre,ins,strlen(pre)); last(root); cout<<endl; level(root); cout<<endl; } return 0; }
标签:node 0ms pac 第一个 建二叉树 amp tree 字符 stdio.h
原文地址:http://www.cnblogs.com/ljbguanli/p/7222520.html