根据先序和中序序列 输出树的高度

输入先序和中序序列:

7
4 1 3 2 6 5 7
1 2 3 4 5 6 7

输出高度:

4

     

#include<iostream>
using namespace std;
struct node{
	char data;
	node* lchild;
	node* rchild;
};
int pre[55],in[55];
node* buildtree(int prel,int prer,int inl,int inr)
{
	if(inl>inr) return NULL;
	node* root=new node;
	root->data=pre[prel];
	int i;
	for(i=inl;i<=inr;i++)
	{
		if(in[i]==pre[prel])
		   break;
	}
	int num=i-inl;
	root->lchild=buildtree(prel+1,prel+num,inl,i-1);
	root->rchild=buildtree(prel+num+1,prer,i+1,inr);
}
int GetHeight(node* root)
{
	int h1,h2,MaxH;
	if(root)
	{
		h1=GetHeight(root->lchild);
		h2=GetHeight(root->rchild);
		MaxH=h1>h2?h1:h2;
		return MaxH+1;
	}
}
int main()
{
	int n,i;
	scanf("%d",&n);
	for(int i=1;i<=n;i++)
	   scanf("%d",&pre[i]);
	for(int i=1;i<=n;i++)
	   scanf("%d",&in[i]);
	node*root=buildtree(1,n,1,n);
    int h=GetHeight(root);
    cout<<h<<endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/daoshen1314/article/details/88314131