【摘要】 二叉树,根据先序、中序序列,求后续遍历结果
输入:
第一行为二叉树先序遍历结果。
第二行为二叉树中序遍历结果。
12
输出:
二叉树后续遍历结果
1
样例输入:
426315
623415
12
样例输出:
632514
1
完整代码:
#include<bits/stdc++.h>
using namespace std;char pre[10…
二叉树,根据先序、中序序列,求后续遍历结果
输入:
第一行为二叉树先序遍历结果。
第二行为二叉树中序遍历结果。
输出:
二叉树后续遍历结果
样例输入:
426315
623415
样例输出:
632514
完整代码:
#include<bits/stdc++.h>
using namespace std;
char pre[100];
char hou[100];
//定义结构体
typedef struct node{
char data;
struct node *lc,*rc;
} *BTree;
//根据先序、中序建树
BTree build(int l1, int r1, int l2, int r2){
BTree T = new node;
T->data = pre[l1];
T->lc=NULL;
T->rc=NULL;
int pos = l2;
while(hou[pos]!=pre[l1]){
pos++;
}
int cnum = pos-l2;
if(pos>l2){
T->lc = build(l1+1, l1+cnum, l2, pos-1);
}
if(pos<r2){
T->rc = build(l1+cnum+1, r1, pos+1, r2);
}
return T;
}
//后续输出遍历结果
void Hou(BTree T){
if(T!=NULL){
Hou(T->lc);
Hou(T->rc);
cout<<T->data;
}
}
//主函数
int main(){
cin>>pre;
cin>>hou;
BTree T = build(0, strlen(pre)-1, 0, strlen(hou)-1);
Hou(T);
}
文章来源: blog.csdn.net,作者:贴地飞行lyh,版权归原作者所有,如需转载,请联系作者。
原文链接:blog.csdn.net/qq_43279324/article/details/116785813
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END