first root

时间:2022-07-02 13:00:33

题目给出一棵二叉树的中序和后序排列。求出它的先序排列【提示】通过对比二叉树的中序和后序排列,我们可以找出根节点及左右子树。同样的,也可以通过对比左子树的中序和后序排列,找出左子树的根节点…….可见,该问题能够被递归描述。当找到最后一个根节点时,递归无法再进行下去,这就是递归结束的边界条件。

(1)输入://中序 b  a  c

//后序 b c  a

输出://先序 a  b  c

(2)输入://中序 c  b e  g  d f  a

//后序 c  g  e f   d  b  a

/输出://先序 a  b c  d   e g  f

分析:此题主要方向是利用指针和数组地址的连续性,先找后序序列中最后一个节点,即寻根操作;找到根节点后输出,即按照先根遍历规则:“根左右”;其后将左右子树切割开,先左后右进行递归输出。

#include<cstdio>
#include<cstdlib>
#include<cstring>
using namespace std;
void first_root(char *mid_s,char *last_s)
{
if(!*mid_s)return;
char t,*p,*q;
p=last_s+strlen(last_s)-1;
printf("%c",*p);
q=strchr(mid_s,*p);
*p=0;
p=q-mid_s+last_s;
t=*p;
*p=*q=0;
first_root(mid_s,last_s);
*p=t;
first_root(q+1,p);
}
int main()
{
char mid_s[1001],last_s[1001];
scanf("%s%s",mid_s,last_s);
first_root(mid_s,last_s);
return 0;
}