# 中序和先序、中序和后序

25 篇文章 4 订阅

## 中序和后序

Lnode CreateBTree(char inOd[], char postOd[], int n)
{
if (n == 0)
return nullptr;
Lnode btRoot = new Node;
btRoot->data = postOd[n-1];     //后序序列最后一个元素一定是根节点
char lInOd[MAX_SIZE], rInOd[MAX_SIZE];
char lPostOd[MAX_SIZE], rPostOd[MAX_SIZE];
int n1, n2;
n1 = n2 = 0;
//根据根节点将中序序列分为左子树和右子树
for (int i = 0; i < n; i++)
{
if (i <= n1 && inOd[i] != btRoot->data)
lInOd[n1++] = inOd[i];
else if (inOd[i] != postOd[n-1])//跳过根结点
rInOd[n2++] = inOd[i];
}
//根据一个树的后序序列的长度等于中序序列且后序遍历是先左子树再右子树
//将后序序列分为左子树和右子树
int m1, m2;
m1 = m2 = 0;
for (int i = 0; i < n-1; i++)
{
if (i < n1)
lPostOd[m1++] = postOd[i];
else
rPostOd[m2++] = postOd[i];
}
btRoot->lchild = CreateBTree(lInOd, lPostOd, n1);
btRoot->rchild = CreateBTree(rInOd, rPostOd, n2);
return btRoot;
}



## 先序和中序

#include<iostream>
using namespace std;
#define MAX_SIZE 1000
typedef struct Node{
char data;
struct Node *lchild,*rchild;
}Node,*Lnode;
{
Node data;
//这个表示队列的数据结构中只有front和rear

Lnode CreateBTree(char *Pre,char * In,int length);
void PreOrder(Lnode root);
//void LevelOrder(Lnode root);
/*void visit(Lnode node);
bool DeQueue(LinkQueue & Q,Node & x);*/

int main()
{
Lnode root=nullptr;
char Pre[MAX_SIZE],In[MAX_SIZE];
char ch;
int n = 0;
while((ch=getchar())&&ch!='\n')
Pre[n++] = ch;
n=0;
while((ch=getchar())&&ch!='\n')
In[n++] = ch;
root = CreateBTree(Pre, In, n);
//LevelOrder(root);
PreOrder(root);
return 0;
}

Lnode CreateBTree(char* Pre,char* In,int length)
{
if(length==0)
return nullptr;
Lnode root = new Node;
root->data = Pre[0];
int n1,n2;
n1 = n2 =0;
char  lPre[MAX_SIZE],rPre[MAX_SIZE],lIn[MAX_SIZE],rIn[MAX_SIZE];
//中序序列分组
for (int i = 0; i < length; i++)
{
if (i <= n1 && In[i] != root->data)
lIn[n1++] = In[i];
else if (In[i] != root->data)
rIn[n2++] = In[i];
}
/*while(In[n]!=root->data)
{
lIn[n1++]=In[n++];
}
n++;
while(n<length)
{
rIn[n2++]=In[n++];
}*/
//前序序列分组
int m1,m2;
m1 = m2 =0;
/*while(n<length)
{
if(n<=n1)
lPre[m1++] = Pre[n++];
rPre[m2++] = Pre[n++];
}
*/
for(int i = 1;i < length;i++)
{
if(i < n1)
lPre[m1++] = Pre[i];
else
rPre[m2++] = Pre[i];
}
root->lchild = CreateBTree(lPre,lIn,n1);
root->rchild = CreateBTree(rPre,rIn,n2);
return root;
}

void PreOrder(Lnode root)
{
if(root==nullptr)
return;
cout<<root->data<<" ";
PreOrder(root->lchild);
PreOrder(root->rchild);

}


03-21 2370

02-28 5798
03-03 3万+
10-09 5706
06-08 41万+
11-04 1954
07-29 1703
01-25 1559
01-07 346
09-09 1168
01-26 7560
05-25 635
04-29 775

### “相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

¥2 ¥4 ¥6 ¥10 ¥20

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。