#include <bits/stdc++.h>
using namespace std;
int post[50] , ino[50]; //定义全局变量
typedef struct btnode {
int data;
struct btnode *lchild,*rchild;
}btnode , *btree;
btree buildetree(int root,int start,int end);//root为后序根节点,start为中序开始,end为中序结尾
void DLRtree(btree bt);
int main(){
btree bt;
int N; cin>>N;
int i;
for(i=0;i<N;i++){
int x; cin>>x;
post[i] = x;
}
for(i=0;i<N;i++){
int x; cin>>x;
ino[i] = x;
}
bt = buildetree(N-1,0,N-1);//root在第N-1个位置,start开始在0位置,end在第N-1个位置
cout<<"Preorder:";
DLRtree(bt);
return 0;
}
btree buildetree(int root,int start,int end){
if(start>end) return 0;
btree bt;
int i;
for(i=start;post[root] !=ino[i];i++);
bt = new btnode;
bt->data = post[root];
bt->lchild = buildetree(root-(end-i)-1,start,i-1);
bt->rchild = buildetree(root-1,i+1,end);
//下面图片
return bt;
}
void DLRtree(btree bt){
if(bt == NULL) return;
cout<<" "<<bt->data ;
DLRtree(bt->lchild );
DLRtree(bt->rchild );
}
![寻找root,statr,end的图](https://img-blog.csdnimg.cn/2020111817405153.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L20wXzUxMTk5MzA0,size_16,color_FFFFFF,t_70#pic_center)
4-15 根据后序和中序遍历输出先序遍历 (15分)本题要求根据给定的一棵二叉树的后序遍历和中序遍历结果,输出该树的先序遍历结果。
最新推荐文章于 2023-11-20 22:47:47 发布