二叉树输出(凹入表示法)

来源:互联网 发布:北京云计算公司 编辑:程序博客网 时间:2024/05/01 22:04


二叉树输出(凹入表示法)

题目描述

1598:二叉树输出

时间限制:1 Sec  内存限制:128 MB
提交:8  解决:8
[提交][状态][讨论版]

题目描述

树的凹入表示法主要用于树的屏幕或打印输出,其表示的基本思想是兄弟间等长,一个结点要不小于其子结点的长度。二叉树也可以这样表示,假设叶结点的长度为1,一个非叶结点的长并等于它的左右子树的长度之和。
一棵二叉树的一个结点用一个字母表示(无重复),输出时从根结点开始: 
每行输出若干个结点字符(相同字符的个数等于该结点长度)
如果该结点有左子树就递归输出左子树; 
如果该结点有右子树就递归输出右子树。
假定一棵二叉树一个结点用一个字符描述,现在给出先序和中序遍历的字符串,用树的凹入表示法输出该二叉树。

输入

输入共两行,每行是由字母组成的字符串(一行的每个字符都是唯一的)分别表示二叉树的先序遍历和中序遍历的序列。

输出

输出的行数等于该树的结点数,每行的字母相同。

样例输入

ABCDEFG 
CBDAFEG 

样例输出

AAAA
BB
C
D
EE
F
G

提示

来源

信息学奥赛一本通

[提交][状态][讨论版]

 代码如下

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

#include<cstdio>

#include<cstring>

#include<cmath>

usingnamespacestd;

charchuan1[1010],chuan2[1010]

intn;

structnode{

 charch;

 intdata;

 intxian,rightchild,t;

}node[101];

voidcreat(intxianxushou,intxianxumo,intzhongxushou,intzhongxumo,intx){

    inttemp,k=0,i,temp2,temp3;

    for(i=1;i<=n;i++) if(chuan2[i]==chuan1[xianxushou]) temp=i;

    node[xianxushou].ch=chuan1[xianxushou];

    node[xianxushou].xian=x;

    if(temp==zhongxumo&&temp==zhongxushou) node[xianxushou].t=1;

    elsenode[xianxushou].t=0;

if(temp>zhongxushou)

creat(xianxushou+1,xianxushou+temp-zhongxushou,zhongxushou,temp-1,xianxushou);

if(temp<zhongxumo) 

creat(xianxushou+temp-zhongxushou+1,xianxumo,temp+1,zhongxumo,xianxushou);

}//看下面题解

intmain(){

    inti;

    scanf("%s",chuan1+1);

    scanf("%s",chuan2+1);

    n=strlen(chuan1+1);

    creat(1,n,1,n,0);

    for(i=n;i>=1;i--) if(node[i].xian>=0) node[node[i].xian].t+=node[i].t;

    for(i=1;i<=n;i++) {

        for(intj=1;j<=node[i].t;j++) printf("%c",node[i].ch);

        printf("\n");

    }

}

 

 

 

小小题解——关于先序、中序简述问题(以样例为例)

A

B

C

D

E

F

G

 

 

 

先序

C

B

D

A

F

E

C

 

 

 

中序                                  temp

Creat(先序首,先序末,中序首,中序末)

首先,易得A为树根,那么在中序中查询可知temp=4

因为中序的性质,所以A的左子树有三个,右子树有四个

那么我们返回先序序列,有先序的性质易得先序【2-4】为左子树先序【5-7】为右子树

每个子树的第一个一定是该子树的根,然后又返回中序队列查询

最后可抽象出creat函数

creat(intxianxushou,intxianxumo,intzhongxushou,intzhongxumo,intx)

 

在先序队列xianxushou-xianxumo和中序队列zhongxushou-zhongxumo中进行查找

0 0
原创粉丝点击