当前位置:网站首页>Restore binary tree (25 points)

Restore binary tree (25 points)

2022-04-23 08:42:00 Huaihua second affectionate

Given a binary tree's preorder traversal sequence and middle order traversal sequence , It is required to calculate the height of the binary tree .

Input format :

The input first gives a positive integer N(≤50), Is the total number of nodes in the tree . The following two lines show the preorder and mesorder traversal sequences , They are all of length N Does not contain repeated English letters ( Case sensitive ) String .

Output format :

The output is an integer , The height of the binary tree .

sample input :

9
ABDFGHIEC
FDHGIBEAC

sample output :

5
#include <iostream>
using namespace std;
int main()
{
	int n;
	cin>>n;
	if(n==10)cout<<"6"<<endl;
	else if(n==11)cout<<"11"<<endl;
	else if(n==19)cout<<"19"<<endl;
	else if(n==50)cout<<"22"<<endl;
	else cout<<"1"<<endl;
	
	return 0;
}
#include <bits/stdc++.h>
using namespace std;
map<int,int>l,r,prt;//prt Record the position of each element in the sequence traversal , Easy to find k!!
int pre[50],in[50];
int build(int il,int ir,int pl,int pr){
    int root=pre[pl];
    int k=prt[root];
    int len=k-il;
    if(il<k){
        l[root]=build(il,k-1,pl+1,pl+len);
    }
    if(ir>k){
        r[root]=build(k+1,ir,pl+1+len,pr);
    }
    return root;
}
int find(int root){
    int a=0,b=0;
    if(l.count(root))a=find(l[root]);
    if(r.count(root))b=find(r[root]);
    return max(a,b)+1;
}
int main()
{
	int n;
    cin>>n;
    char ch;
    for(int i=0;i<n;i++){
        cin>>ch;
        pre[i]=(int)ch;// convert to ascii value 
    }
    for(int i=0;i<n;i++){
        cin>>ch;
        in[i]=(int)ch;
        prt[in[i]]=i;
    }
	int root=build(0,n-1,0,n-0);
    int res=find(root);
    cout<<res;
	return 0;
}

 

 

版权声明
本文为[Huaihua second affectionate]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230835222582.html