1. 程式人生 > >7-23 還原二叉樹(25 分)

7-23 還原二叉樹(25 分)

else int font 區別 printf 根節點 break ++ 輸出格式

給定一棵二叉樹的先序遍歷序列和中序遍歷序列,要求計算該二叉樹的高度。

輸入格式:

輸入首先給出正整數N(≤50),為樹中結點總數。下面兩行先後給出先序和中序遍歷序列,均是長度為N的不包含重復英文字母(區別大小寫)的字符串。

輸出格式:

輸出為一個整數,即該二叉樹的高度。

輸入樣例:

9
ABDFGHIEC
FDHGIBEAC

輸出樣例:

5
解題思路:先序中第一個字母A為根節點,因而中序的第一個字母到A為A的左子樹,A以後的字母為A的右子樹,遞歸可建二叉樹
 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 #include<string
.h> 4 5 typedef struct TNode 6 { 7 char data; 8 struct TNode *lchild,*rchild; 9 } TNode,*Tree; 10 11 Tree CreatTree( char xian[],char zhong[],int n); 12 int High( Tree t); 13 14 char xian[55]; //先序序列 15 char zhong[55]; //後序序列 16 int n; 17 18 int main() 19 { 20 scanf("%d",&n);
21 scanf("%s",xian); 22 scanf("%s",zhong); 23 Tree tree = CreatTree( xian,zhong,n); 24 printf("%d",High(tree)); 25 return 0; 26 } 27 28 Tree CreatTree( char xian[],char zhong[],int n) 29 { 30 if( n==0 ) return NULL; 31 int index = 0; 32 Tree temp = (Tree) malloc(sizeof(struct
TNode)); 33 34 while( index < n) 35 { 36 if( zhong[index]==xian[0]) break; 37 index ++; 38 } 39 temp->data = xian[0]; 40 temp->lchild = CreatTree(xian+1,zhong,index); 41 temp->rchild = CreatTree(xian+1+index,zhong+index+1,n-index-1); 42 return temp; 43 } 44 45 int High( Tree t) 46 { 47 if( !t ) return 0; 48 int lh = High(t->lchild); 49 int rh = High(t->rchild); 50 if( lh>rh ) return ++lh; 51 else return ++rh; 52 }






7-23 還原二叉樹(25 分)