7-23 还原二叉树(25 分)
给定一棵二叉树的先序遍历序列和中序遍历序列,要求计算该二叉树的高度。
输入格式:
输入首先给出正整数N(≤50),为树中结点总数。下面两行先后给出先序和中序遍历序列,均是长度为N的不包含重复英文字母(区别大小写)的字符串。
输出格式:
输出为一个整数,即该二叉树的高度。
输入样例:
9
ABDFGHIEC
FDHGIBEAC
输出样例:
5
二叉树构造老方法,递归构造,注意找先序序列和中序序列中子树的下标范围。高度计算:二叉树高度=max(左子树高度,右子树高度)+1 ,注意节点指针==NULL时,返回0。
#include <iostream> #include <cstdio> #include <algorithm> #include <string> #include <vector> #include <sstream> #include <map> #include <queue> #include <stack> #include <cstring> #include <set> #define INF 1000000 using namespace std; struct Btree { char c; Btree *left; Btree *right; Btree (char aa) { c=aa; left=right=NULL; } }; int Find(char x,char *zhong,int n) { for(int i=0;i<n;i++) { if(zhong[i]==x) { return i; } } } Btree *build(int n,char *xian,char *zhong) { if(n==0) return NULL; char c=xian[0]; int index=Find(c,zhong,n); Btree *tmp=new Btree(c); tmp->left=build(index,xian+1,zhong); tmp->right=build(n-index-1,xian+1+index,zhong+1+index); return tmp; } int solve(Btree *r) { if(r==NULL) return 0; int tmp1=solve(r->left); int tmp2=solve(r->right); return max(tmp1,tmp2)+1; } int main() { int n; char xian[100]; char zhong[100]; scanf("%d",&n); scanf("%s",xian); scanf("%s",zhong); Btree *root=build(n,xian,zhong); int h=solve(root); printf("%d\n",h); return 0; }