#include<stdio.h>
#include<stdlib.h>
typedef struct node{
char data;
struct node* left;
struct node* right;
} node;
int GetHeight(node* root) {
int hl, hr, maxh;
if (root == NULL) return 0;
hl = GetHeight(root->left);
hr = GetHeight(root->right);
maxh = hl > hr ? hl : hr;
return maxh + 1;
}
node* maketree(char* preorder,char* inorder,int n){
if(n==0) return NULL;
node*root=(node*)malloc(sizeof(node));
root->data=preorder[0];
int i=0;
while(preorder[0]!=inorder[i]) i++;
root->left=maketree(preorder+1,inorder,i);
root->right=maketree(preorder+i+1,inorder+i+1,n-i-1);
return root;
}
int main(){
int n;
scanf("%d",&n);
char* preorder=(char*)malloc(sizeof(char)*n);
char* inorder=(char*)malloc(sizeof(char)*n);
scanf("%s",preorder);
scanf("%s",inorder);
node* root=maketree(preorder,inorder,n);
printf("%d",GetHeight(root));
return 0;
}
PTA 7-1 还原二叉树
最新推荐文章于 2024-07-18 16:41:02 发布