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

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

ica data ext ble 序列 col 小寫 先後 span

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

輸入格式:

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

輸出格式:

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

輸入樣例:

9
ABDFGHIEC
FDHGIBEAC

輸出樣例:

5


代碼:

#include <stdio.h>
#include <stdlib.h>

char x[50],z[50];
typedef struct TreeNode *Tree;
struct TreeNode { char data; Tree right,left; }; Tree CreatNode() { Tree p = (Tree)malloc(sizeof(struct TreeNode)); p -> left = p -> right = NULL; return p; } Tree RestoreTree(int x1,int x2,int z1,int z2) { Tree head = CreatNode(); head -> data = x[x1];
for(int i = z1;i <= z2;i ++) { if(z[i] == x[x1]) { if(i != z1)head -> left = RestoreTree(x1 + 1,x1 + i - z1,z1,i - 1); if(i != z2)head -> right = RestoreTree(x1 + i - z1 + 1,x2,i + 1,z2); break; } } return head; }
int max(int a,int b) { if(a>b)return a; return b; } int Theight(Tree tree) { if(tree == NULL)return 0; return max(Theight(tree -> left),Theight(tree -> right))+1; } int main() { int n; scanf("%d",&n); scanf("%s%s",x,z); Tree head = RestoreTree(0,n-1,0,n-1); printf("%d",Theight(head)); }

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