二叉树输出(凹入表示法)
二叉樹輸出(凹入表示法)
題目描述
1598: 二叉樹輸出
 時間限制:1 Sec??內存限制: 128 MB
 提交:8??解決: 8
 [提交][狀態(tài)][討論版]
題目描述
樹的凹入表示法主要用于樹的屏幕或打印輸出,其表示的基本思想是兄弟間等長,一個結點要不小于其子結點的長度。二叉樹也可以這樣表示,假設葉結點的長度為1,一個非葉結點 的長并等于它的左右子樹的長度之和。
 一棵二叉樹的一個結點用一個字母表示(無重復),輸出時從根結點開始:?
 每行輸出若干個結點字符(相同字符的個數(shù)等于該結點長度),
 如果該結點有左子樹就遞歸輸出左子樹;?
 如果該結點有右子樹就遞歸輸出右子樹。
 假定一棵二叉樹一個結點用一個字符描述,現(xiàn)在給出先序和中序遍歷的字符串,用樹的凹入表示法輸出該二叉樹。
輸入
輸入共兩行,每行是由字母組成的字符串(一行的每個字符都是唯一的), 分別表示二叉樹的先序遍歷和中序遍歷的序列。
輸出
輸出的行數(shù)等于該樹的結點數(shù),每行的字母相同。
樣例輸入
ABCDEFG CBDAFEG樣例輸出
AAAA BB C D EE F G提示
來源
信息學奧賽一本通
[提交][狀態(tài)][討論版]
?代碼如下
| 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> using namespace std; char chuan1[1010],chuan2[1010] int n; struct node{ ?char ch; ?int data; ?int xian,rightchild,t; }node[101]; void creat(int xianxushou,int xianxumo,int zhongxushou,int zhongxumo,int x){ ????int temp,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; ????else node[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); }//看下面題解 int main(){ ????int i; ????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(int j=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函數(shù)
creat(int xianxushou,int xianxumo,int zhongxushou,int zhongxumo,int x)
?
在先序隊列xianxushou-xianxumo和中序隊列zhongxushou-zhongxumo中進行查找
總結
以上是生活随笔為你收集整理的二叉树输出(凹入表示法)的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 「CSA49」Bunny on Numb
- 下一篇: 商品cta策略_《衍生品系列研究之三》:
