pta7-23 还原二叉树 (25分)

#include
#include
#include

typedef struct TNode* BTree;
typedef char ElementType;
struct TNode
{
	ElementType Data;
	BTree Left;
	BTree Right;
};
char pre[100];
char in[100];

BTree Create(int preL,int preR,int inL,int inR)
{
	
	if(preL>preR) return NULL;
	
	BTree root=(BTree)malloc(sizeof(struct TNode));
	root->Data=pre[preL];
	int k;
	for(int i=inL;i<=inR;i++)
	{
		if(pre[preL]==in[i] )
		{
			k=i;
			break;
		}
	}
	int numLeft=k-inL;
    root->Left=Create(preL+1,preL+numLeft,inL,k-1);
	root->Right=Create(preL+numLeft+1,preR,k+1,inR);
	
	return root;
}
int BtDepth(BTree BT)
{
	int HL,HR,MaxH;
	if(BT)
	{
		HL=BtDepth(BT->Left);
		HR=BtDepth(BT->Right);
		MaxH= HR>HL?HR:HL;
		return MaxH+1; 
	}
	else
	return 0;
	
}
int main()
{	
  	int n;
  	scanf("%d",&n);
  	scanf("%s",pre);
  	scanf("%s",in);
  	int len1=strlen(pre);
  	int len2=strlen(in);
  	BTree BT;
  	BT=Create(0,len1-1,0,len2-1);
  	int H=BtDepth(BT);
  	printf("%d\n",H);
  	return 0;
  	
}

参考博文https://blog.csdn.net/qq_42815188/article/details/99122312?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.nonecase&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.nonecase 

 

你可能感兴趣的:(数据结构)