7-5 還原二叉樹 (25 分)(二叉樹,根據 中序遍歷 和 先序遍歷)
阿新 • • 發佈:2018-12-12
7-5 還原二叉樹 (25 分)
給定一棵二叉樹的先序遍歷序列和中序遍歷序列,要求計算該二叉樹的高度。
輸入格式:
輸入首先給出正整數N(≤50),為樹中結點總數。下面兩行先後給出先序和中序遍歷序列,均是長度為N的不包含重複英文字母(區別大小寫)的字串。
輸出格式:
輸出為一個整數,即該二叉樹的高度。
輸入樣例:
9
ABDFGHIEC
FDHGIBEAC
輸出樣例:
5
#include<iostream> #include<vector> #include<cstdio> #include<set> #include<map> #include<string> #include<string.h> #include<algorithm> #include<cmath> #include<stdlib.h> #include<ctype.h> #include<stack> #include<queue> #include<list> using namespace std; typedef struct node{ struct node* left; struct node* right; char data; }node; node* BitryTree(char a[],char b[],int n){ node *T; int i; if(!n) return NULL; else{ T = (node *)malloc(sizeof(struct node)); T->data = a[0]; for(i=0;i<n;i++){ if(a[0]==b[i]) break; } T->left = BitryTree(a+1,b,i); T->right = BitryTree(a+1+i,b+i+1,n-i-1); } return T; }; int getHight(node* T){ int hl,hr,hight; if(!T) return 0; else{ hl=getHight(T->left); hr=getHight(T->right); hight=hl>hr?hl:hr; hight++; } return hight; } int main(){ int n; char a[55]; char b[55]; scanf("%d",&n); scanf("%s",a); scanf("%s",b); node *tree = BitryTree(a,b,n); int hight = getHight(tree); cout<<hight<<endl; return 0; }