天天看點

還原二叉樹PTA

給定一棵二叉樹的先序周遊序列和中序周遊序列,要求計算該二叉樹的高度。

輸入格式:

輸入首先給出正整數N(≤50),為樹中結點總數。下面兩行先後給出先序和中序周遊序列,均是長度為N的不包含重複英文字母(差別大小寫)的字元串。

輸出格式:

輸出為一個整數,即該二叉樹的高度。

輸入樣例:

9
ABDFGHIEC
FDHGIBEAC
           

輸出樣例:

代碼:

#include<stdio.h>
#include<stdlib.h>
#define MAX 51

typedef char ElementType;
typedef struct node * BinTree;
struct node{
	ElementType Data;
	BinTree zuo; //左子樹
	BinTree you; //右子樹
};

BinTree Recover(ElementType Pre[MAX],ElementType In[MAX],int len); //建立二叉樹
int GetHigh(BinTree T); //計算高度

int main()
{
	BinTree Tree;
	ElementType xianxu[MAX],zhongxu[MAX];
	int N,H;
	scanf("%d%s%s",&N,xianxu,zhongxu);
	Tree=Recover(xianxu,zhongxu,N);
	H=GetHigh(Tree);
	printf("%d\n",H);
	return 0;
}
BinTree Recover(ElementType Pre[MAX],ElementType In[MAX],int len) //建立二叉樹 
{
	BinTree T;
	int i;
	if(!len)return NULL; //如果二叉樹不存在,則高度為0 
	else
	{
		T=(BinTree)malloc(sizeof(struct node));
		T->Data=Pre[0]; //根據先序周遊結果确定根結點 
		for(i=0;i<len;i++) //在中序周遊結果中确定根結點的位置 
		{
			if(Pre[0]==In[i])break;
		}
		T->zuo=Recover(Pre+1,In,i); //由根結點分,分别建立左子樹和右子樹 
		T->you=Recover(Pre+1+i,In+i+1,len-i-1);
	}
	return T;
}
int GetHigh(BinTree T) //計算高度 
{
	int l,r,max;
	if(T)
	{
		l=GetHigh(T->zuo);
		r=GetHigh(T->you);
		max=l>r? l:r;
		return max+1;
	}
	else return 0;
}
}
           
還原二叉樹PTA

繼續閱讀