注意,用前序找根节点,然后在中序中查找,然后将二叉树分为左子树和右子树存入新建的树中,然后递归循环,分别又在两个子树中找根节点,继续分,一直递归,直到节点个数没有,停止递归,返回新树。
数据结构实验之求二叉树后序遍历和层次遍历
Time Limit: 1000MS Memory limit: 65536K
题目描述
已知一棵二叉树的前序遍历和中序遍历,求二叉树的后序遍历。
输入
输入数据有多组,第一行是一个整数t (t<1000),代表有t组测试数据。每组包括两个长度小于50 的字符串,第一个字符串表示二叉树的先序遍历序列,第二个字符串表示二叉树的中序遍历序列。
输出
每组第一行输出二叉树的后序遍历序列,第二行输出二叉树的层次遍历序列
示例输入
2 abdegcf dbgeafc xnliu lnixu
示例输出
dgebfca abcdefg linuxxnuli
#include <iostream> #include <algorithm> #include<cstring> #include<queue> using namespace std; typedef struct node { char data; struct node *lchild,*rchild; } node ,*tree; tree yuancreat(char *s,char *t,int n); void posorder(tree t); void levelorder(tree t); int main() { tree tre; char s[60],r[60]; int a,l1; cin>>a; tre=(tree)malloc(sizeof(node)); while(a--) { cin>>s; cin>>r; l1=strlen(s); tre=yuancreat(s,r,l1); posorder(tre); cout<<endl; levelorder(tre); cout<<endl; } } tree yuancreat(char *s,char *r,int n) { tree t; char *p; if(n<=0) return NULL; t=(tree)malloc(sizeof(node)); if(!t) exit (0); t->data=s[0]; //取根节点进入树 for(p=r; p!='\0'; p++) { //cout<<p<<endl; //cout<<" "<<*p<<endl;注p++相当于i后移,*p取p的第一个值 if(*p==*s) break;//查找根节点 } int ln=p-r;//遍历到中间根节点,左边的数值的个数 t->lchild=yuancreat(s+1,r,ln); t->rchild=yuancreat(s+ln+1,p+1,n-ln-1); return t; } void posorder(tree t) { if(t!=NULL) { posorder(t->lchild); posorder(t->rchild); cout<<t->data; } } void levelorder(tree t) { tree p=t; queue<tree>sq; if(p)//注意,如果没有会超时 sq.push(p); while(!sq.empty()) { p=sq.front(); cout<<p->data; sq.pop(); if(p->lchild!=NULL) sq.push(p->lchild); if(p->rchild!=NULL) sq.push(p->rchild); } }