7-1 还原二叉树 (25 分)
给定一棵二叉树的先序遍历序列和中序遍历序列,要求计算该二叉树的高度。
输入格式:
输入首先给出正整数N(≤50),为树中结点总数。下面两行先后给出先序和中序遍历序列,均是长度为N的不包含重复英文字母(区别大小写)的字符串。
输出格式:
输出为一个整数,即该二叉树的高度。
输入样例:
9
ABDFGHIEC
FDHGIBEAC
输出样例:
5
上代码:
#include <bits/stdc++.h>
using namespace std;
struct treeNode{
char Data;
struct treeNode *right;
struct treeNode *left;
};
typedef struct treeNode* Node;
Node createTree(char *X,char *Z,int temp){
Node root=(Node)malloc(sizeof(struct treeNode));
if(temp==0)return NULL;
root->left=NULL;
root->right=NULL;
root->Data=*X;
int k;
for(int i=0;i<temp;i++){
if(*X==*(Z+i))
{k=i;break;}
}
//cout<<temp<<" "<<k<<endl;
root->left=createTree(X+1,Z,k);
root->right=createTree(X+k+1,Z+k+1,temp-k-1);
return root;
}
void houxubianli(Node root)
{
if(root==NULL)return;
if(root->left!=NULL)
houxubianli(root->left);
if(root->right!=NULL)
houxubianli(root->right);
cout<<root->Data<<" ";
}
int high(Node root)
{
if(root==NULL)return 0;
int max=high(root->left);
if(max<high(root->right))
max=high(root->right);
return max+1;
}
int main()
{
int N;
cin>>N;
char xx[N];
char zx[N];
for(int i=0;i<N;i++)
cin>>xx[i];
for(int i=0;i<N;i++)
cin>>zx[i];
Node Root=createTree(xx,zx,N);
cout<<high(Root);
return 0;
}