王道机试例3.4
不同与王道例题的写法,用考研时习惯的代码书写方法
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
char pre[26];///前序遍历输入
char in[26];///中序遍历输入
typedef struct BiNode
{
char data;
struct BiNode *lchild,*rchild;
}BiNode,*BiTree;
BiNode *CreatBiTree(char pre[],char in[],int l1,int r1,int l2,int r2)
{
///用前序遍历和中序遍历创建一个二叉树,l1,r1为前序遍历数组头尾指针,l2,r2为后序遍历数组头尾指针
if(l1>r1)
{
return NULL;
}
BiNode *s;
int i;
s=(BiTree)malloc(sizeof(BiNode));
s->data=pre[l1];
s->lchild=NULL;
s->rchild=NULL;
for(i=l2;in[i]!=pre[l1]&&i<=r2;i++)///i<=r2 取大于等于 i从l2开始(不必从0开始遍历 太慢了)
{
if(in[i]==pre[l1])
{
break;
}
}
s->lchild=CreatBiTree(pre,in,l1+1,l1+i-l2,l2,i-1);
s->rchild=CreatBiTree(pre,in,l1+i-l2+1,r1,i+1,r2);
return s;
}
BiNode* CreatTree(char pre[],char in[],int n)
{
int l1=0;
int r1=n-1;
int l2=0;
int r2=n-1;
return CreatBiTree(pre,in,l1,r1,l2,r2);
}
void post_order (BiTree T)
{
if(T!=NULL)
{
post_order(T->lchild);
post_order(T->rchild);
printf("%c",T->data);
}
}
int main()
{
int n=0;///表示结点数
BiTree T;
scanf("%s",pre);
scanf("%s",in);
for(int i=0;pre[i]!=0;i++)
{
n++;
}
T=CreatTree(pre,in,n);
post_order(T);
printf("\n");
return 0;
}
若要使用malloc函数 记得加入库stdlib.h
#include <stdlib.h>
在CreatBiTree()函数中
s->lchild=CreatBiTree(pre,in,l1+1,l1+i-l2,l2,i-1);
s->rchild=CreatBiTree(pre,in,l1+i-l2+1,r1,i+1,r2);
其中i即对应着这里的j ,那为什么函数的r1参数变化不用i而用l1+i-l2呢?
是因为i是中序遍历的下标,直接用i不是在前序序列中对应的位置。
i-l2是左子树的长度
l1+i-l2则是左子树的尾
l1+i-l1+1则是右子树的头