7-23 还原二叉树(25 分)
给定一棵二叉树的先序遍历序列和中序遍历序列,要求计算该二叉树的高度。
输入格式:
输入首先给出正整数N(≤50),为树中结点总数。下面两行先后给出先序和中序遍历序列,均是长度为N的不包含重复英文字母(区别大小写)的字符串。
输出格式:
输出为一个整数,即该二叉树的高度。
输入样例:
9
ABDFGHIEC
FDHGIBEAC
输出样例:
5
- 题解:先根据先序和中序遍历建立二叉树,然后递归求得二叉树的深度。
- 代码:
#include <iostream> #include <cstdio> #include <cstring> #include <cmath> #include <algorithm> #include <vector> #include <set> #include <map> using namespace std; typedef struct node{//二叉链表存储 char data; node *lchild,*rchild; }BiTNode,*BiTree; node* create(char pre[],char in[],int n){/递归创建二叉树 if(n<=0) return NULL; int t,root=pre[0]; for(int i=0;i<n;i++){//在中序遍历中寻找当前二叉树的根节点,找到break; if(in[i]==root){ t=i; break; } } BiTree T; T = new BiTNode; T->lchild=NULL; T->rchild=NULL; T->data=root; T->lchild=create(pre+1,in,t);//递归创建左子树 T->rchild=create(pre+t+1,in+t+1,n-t-1);//递归创建右子树 return T; } int depth=0; int getDepth(BiTree T){//求二叉树的深度 if(T==NULL) return 0; int left=getDepth(T->lchild);//递归求左子树的深度 int right=getDepth(T->rchild);//递归求右子树的深度 return 1+(left>right?left:right);//返回二者之间的最大值 } int main() { int n; char pre[55],in[55]; BiTree T; cin>>n; scanf("%s",pre); scanf("%s",in); T = new BiTNode; T->lchild=NULL; T->rchild=NULL; T=create(pre,in,n); printf("%d\n",getDepth(T)); return 0; }