根据后序序列和中序序列创建二叉树
如果代码有错欢迎评论留言
#include<bits/stdc++.h>
using namespace std;
typedef struct node{
int val;
struct node* left;
struct node* right;
}*Bitree;
/*
如果数组p1=1 2 3 4 5
int* p2=p1+2;
p2为3 4 5
*/
Bitree createBitree(int* h,int* z,int size){
//参数1:后续序列,参数2:中序序列,参数3:中序长度//
if(size<1)return NULL;//如果中序长度小于1就表示该结点为空//
Bitree p=(Bitree)malloc(sizeof(struct node));
p->val=h[size-1];//当前后续序列的最后一位就是根结点//
int f=0;//f用来计算当前结点的左子树结点数//
while(z[f]!=h[size-1])f++;//中序序列中当前根结点的左边就是左子树序列//
int r=size-f-1;//中序序列长度减去当前结点左子树长度再减去当前结点就是右子树长度//
p->left=createBitree(h,z,f);//创建左子树//
p->right=createBitree(h+f,z+f+1,r);//创建右子树//
return p;
}
void qdisplay(Bitree t){
if(t==NULL)return ;
else{
cout<<t->val<<' ';
qdisplay(t->left)