PAT 7-23 还原二叉树 (25 分)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_36032963/article/details/84324509

给定一棵二叉树的先序遍历序列和中序遍历序列,要求计算该二叉树的高度。

输入格式:

输入首先给出正整数N(≤50),为树中结点总数。下面两行先后给出先序和中序遍历序列,均是长度为N的不包含重复英文字母(区别大小写)的字符串。

输出格式:

输出为一个整数,即该二叉树的高度。

输入样例:

9
ABDFGHIEC
FDHGIBEAC

输出样例:

5

前序:根、左子树、右子树

中序:左子树、根、右子树

树的高度等于 max(左子树高度,右子树高度)+1  ,递归调用此过程

#include <iostream>  
using namespace std;
int N;
char front[60],mid[60];
int high(char front[], char mid[], int n) {
	if(n==0) return 0;
	int i;
	for(i=0;i<n;i++) 
	  if(front[0]==mid[i]) break;
	return max(high(front+1,mid,i), high(front+i+1,mid+i+1,n-i-1))+1;
}
int main() {
	cin >> N >> front >> mid;
	int high1 = high(front,mid,N);
	cout << high1;
	//system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_36032963/article/details/84324509