4-14 还原二叉树 (15分) 给定一棵二叉树的先序遍历序列和中序遍历序列,要求计算该二叉树的高度。输入首先给出正整数N(≤50),为树中结点总数。下面两行先后给出先序和中序遍历序列,均是长度为N的


#include <bits/stdc++.h>
using namespace std;
char pre[50],ino[50];//定义全局变量
typedef struct btnode{  //定义树的结构体
	char data;
	struct btnode *lchil,*rchil;
}btnode,*btree;
btree buildetree(int root,int start,int end);//root为根结点,start为中序的开始,end为中序的结束
int Gethight(btree t);
int main(){
	btree t; 
	int N; cin>>N;
	int i,j;
	for(i=0;i<N;i++){
		char x; cin>>x;
		pre[i] = x;
	}
	for(j=0;j<N;j++){
		char x; cin>>x;
		ino[j] = x;
	}
	t = buildetree(0,0,N-1); 
	cout<<Gethight(t)<<" ";
	
}

btree buildetree(int root,int start,int end){
	if(start>end) return NULL;
	btree t;
	int i;
	for(i=start;i<=end;i++){ //每次递归start在变所以不从0开始;
	 if(pre[root]==ino[i]) //找到根节点在中序中的位置i
	 break;
	}
	t = new btnode; //分配空间
	t->data = pre[root];
	t->lchil = buildetree(root+1,start,i-1);//先序看出A的左子树根节点位置为root+1;从中序看出A的
	//左子树的开始就是start,结束为A的前一个位置即为i-1;
	t->rchil = buildetree(root+i-start+1,i+1,end);//A的左子树共有i-start个根节点(不用+1因为A不
	//在内)所以A右子树根节点为root+i-start+1,中序右子树开始为i+1,结束为end
	return t;
}
int Gethight(btree t){
	if(t==NULL) return 0;
	int left =  Gethight(t->lchil); //递归求左子树;
	int right =  Gethight(t->rchil);//递归求右子树
	return max(left,right)+1;
}
先序:A __ ___ 中序 __ A ___

输入样例:
9
ABDFGHIEC
FDHGIBEAC
输出样例:
5
  • 6
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值