求二叉树的深度
来源:互联网 发布:英国淘宝 编辑:程序博客网 时间:2024/06/05 17:59
求二叉树的深度
Time Limit: 1000MS Memory limit: 65536K
题目描述
已知一颗二叉树的中序遍历序列和后序遍历序列,求二叉树的深度。
输入
输入数据有多组,输入T组数据。每组数据包括两个长度小于<font face="\"Times" new="" roman,="" serif\"="" style="padding: 0px; margin: 0px;">50的字符串,第一个字符串表示二叉树的中序遍历,第二个表示二叉树的后序遍历。
输出
输出二叉树的深度。
示例输入
2dbgeafcdgebfcalnixulinux
示例输出
43
#include <stdio.h>#include <string.h>#include <stdlib.h>typedef char telemtype;typedef char status;typedef struct bitnode{ telemtype data; struct bitnode *lchild, *rchild;}*bitree;void BinaryTree(bitree& t, char aft[], char ino[],int ps, int is, int length)//ps:后序序列起始位置//is:中序序列起始位置{ if (length==0) t=NULL; else { int k=0; int n = strlen(ino); for(k=0; k<n; k++)//找到根节点在中序序列中的位置,用以划分左右子树 { if(ino[k]==aft[ps+length-1])//后序序列的最后一个元素即为根节点 break; } t= new bitnode; if (!t) exit(0); t->data = aft[ps+length-1]; if (k==is) t->lchild = NULL;//若仅有一个元素,则此结点左子树为空 else BinaryTree(t->lchild, aft, ino, ps, is, k-is); if (k==is+length-1) t->rchild = NULL; //若仅有一个元素,则此结点右子树为空 else BinaryTree(t->rchild, aft, ino, ps+(k-is), k+1, length-(k-is)-1); }}int depth(bitree &t){ int ld, rd; if(!t) return 0; else { ld=depth(t->lchild); rd=depth(t->rchild); if(ld>rd) return ld+1; else return rd+1; }}int main(){ char aft[55], ino[55]; int m; bitree t; scanf("%d", &m); while(m--) { scanf("%s", ino); scanf("%s", aft); int length = strlen(aft); BinaryTree(t, aft, ino, 0, 0, length); printf("%d\n", depth(t)); }}
0 0
- 求二叉树的深度
- 求二叉树的深度
- 求二叉树的深度
- 求二叉树的深度
- 求二叉树的深度
- 求二叉树的深度
- 求二叉树的深度
- 求二叉树的深度
- 求二叉树的深度
- 求二叉树的深度
- 求二叉树的深度
- 求二叉树的深度
- 求二叉树的深度
- 求二叉树的深度
- 求二叉树的深度
- 求二叉树的深度
- 求二叉树的深度
- 求二叉树的深度
- C语言学习9
- sybase的安装使用和视图的创建与维护
- 说清楚重要性采样
- jQuery中Select属性/动态添加/事件
- 非常酷!CSS3三角形运用!
- 求二叉树的深度
- Android 6.0 权限适配说明
- 常见浏览器兼容性问题与解决方案
- Java常见异常(Runtime Exception )小结
- 如何Troubleshooting当Java Application发生死锁或Hangs
- poj 3349 Snowflake Snow Snowflakes
- ZZULI OJ 1899 985的最大和难题
- setValue和setObject的区别
- 模拟一个消息,通知系统SDCard被重新挂载