数据结构实验之二叉树八:(中序后序)求二叉树的深度
来源:互联网 发布:linux crontab 日志 编辑:程序博客网 时间:2024/06/10 03:29
Problem Description
已知一颗二叉树的中序遍历序列和后序遍历序列,求二叉树的深度。
Input
输入数据有多组,输入T,代表有T组数据。每组数据包括两个长度小于50的字符串,第一个字符串表示二叉树的中序遍历,第二个表示二叉树的后序遍历。
Output
输出二叉树的深度。
Example Input
2
dbgeafc
dgebfca
lnixu
linux
Example Output
4
3
#include <iostream>using namespace std;#include <stdio.h>#include <stdlib.h>#include <string.h>#include <cstring>typedef char telemtype;typedef struct Binode{ telemtype data; struct Binode *lchild,*rchild;} Binode,*Bitree;void creat(Bitree &T,telemtype a[],telemtype b[],int n){ int i; if(n==0) T=NULL; else { for(i=0; i<n; i++) { if(a[i]==b[n-1]) break; } T=new Binode; T->data=b[n-1];//n是从1开始的 creat(T->lchild,a,b,i);//a,b都是从左开始。有长度就行 creat(T->rchild,a+i+1,b+i,n-i-1);//n为总个数,i为左子树个数,1为根个数 }}int depth(Bitree T){ int m,n,d; if(!T) d=0; else if(!T->lchild&&!T->rchild) d=1; else { m=depth(T->lchild); n=depth(T->rchild); d=1+(m>n ? m:n);//加上根 } return d;}int main(){ int t; int n; telemtype a[55],b[55]; cin>>t; while(t--) { Bitree T; scanf("%s",a); scanf("%s",b); n=strlen(a);//计算字符串的长度是从1开始的,但是数组是从0开始存的 creat(T,a,b,n); n=depth(T); cout<<n<<endl; } return 0;}
#include <stdio.h>#include <stdlib.h>#include <iostream>#include <string.h>using namespace std;typedef char telemtype;typedef struct Binode{ telemtype data; struct Binode *lchild,*rchild;}Binode,*Bitree;Bitree creat(Bitree &T,telemtype a[],telemtype b[], int n){ int i; if(n==0) T=NULL; else { T=new Binode; T->data=b[n-1]; for(i=0;i<n;i++) { if(a[i]==b[n-1]) break; } T->lchild=creat(T->lchild,a,b,i); T->rchild=creat(T->rchild,a+i+1,b+i,n-i-1); } return T;}int depth(Bitree T){ int d; int m,n; if(!T) d=0; else if(!T->lchild&&!T->rchild) d=1; else { m=depth(T->lchild); n=depth(T->rchild); d=1+(m>n?m:n); } return d;}int main(){ int t; telemtype a[60],b[60]; cin>>t; while(t--) { cin>>a>>b; Bitree T; int n; n=strlen(a); T=creat(T,a,b,n); n=depth(T); cout<<n<<endl; }}
阅读全文
2 0
- 数据结构实验之二叉树八:(中序后序)求二叉树的深度
- SDUT-2804 数据结构实验之二叉树八:(中序后序)求二叉树的深度
- 数据结构实验之二叉树八:(中序后序)求二叉树的深度
- 数据结构实验之二叉树八:(中序后序)求二叉树的深度
- 数据结构实验之二叉树八:(中序后序)求二叉树的深度
- 数据结构实验之二叉树八:(中序后序)求二叉树的深度
- 数据结构实验之二叉树八:(中序后序)求二叉树的深度
- 数据结构实验之二叉树八:(中序后序)求二叉树的深度
- 数据结构实验之二叉树八:(中序后序)求二叉树的深度
- 数据结构实验之二叉树八:(中序后序)求二叉树的深度
- 数据结构实验之二叉树八:(中序后序)求二叉树的深度
- 数据结构实验之二叉树八:(中序后序)求二叉树的深度
- 数据结构实验之二叉树八:(中序后序)求二叉树的深度
- 数据结构实验之二叉树八:(中序后序)求二叉树的深度
- 数据结构实验之二叉树八:(中序后序)求二叉树的深度
- 数据结构实验之二叉树八:(中序后序)求二叉树的深度
- 2804 数据结构实验之二叉树八:(中序后序)求二叉树的深度
- 2804 数据结构实验之二叉树八:(中序后序)求二叉树的深度
- mybatis中#{}【占位符】和${}【字符串】拼接的区别
- 【Java】Java基础知识之HashMap源码分析(Java8)
- 解决主机名问题
- C++ 静态成员变量与静态成员函数
- edittext的requestFocus作用
- 数据结构实验之二叉树八:(中序后序)求二叉树的深度
- init进程与zygote进程
- php安装扩展的几种方法
- Oracle 学习(五)---分页查询
- css轮廓设置
- POI操作word 换行
- HTC Viive实现拧螺丝效果
- v6_pcie_ug517
- C#基础4_数组、方法