数据结构已知中后序列求前序及深度
来源:互联网 发布:加内特总决赛数据 编辑:程序博客网 时间:2024/06/12 23:28
求二叉树的深度
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>#include<malloc.h>int t;int len;char mid[1000],last[1000];struct node{ char data; struct node *lc,*rc;};//还原二叉树法一/*struct node *creat(char mid[],char last[],int len){ if(len==0) { return NULL; } struct node *root; root=(struct node *)malloc(sizeof(struct node)); root->data=last[len-1]; char *p; for(p=mid;p!=NULL;p++) { if(*p==last[len-1]) break; } int t=p-mid; root->lc=creat(mid,last,t); root->rc=creat(p+1,last+t,len-t-1); return root;};*///还原二叉树法二struct node *creat(char mid[],char last[],int len){ if(len==0) { return NULL; } struct node *root; root=(struct node *)malloc(sizeof(struct node)); root->data=last[len-1]; int i; for(i=0;i<len;i++)//从中序中查找与前序中树根节点相同的值 { if(mid[i]==last[len-1]) break; } //通过递归调用查找子数的树根 root->lc=creat(mid,last,i);//无限递归调用左子树 root->rc=creat(mid+i+1,last+i,len-i-1);//无限递归调用右子树 return root;};//前序输出void fristput(struct node *root){ if(root!=NULL) { printf("%c",root->data); fristput(root->lc); fristput(root->rc); }}//深度求解int depth(struct node *root){ if(root==NULL) { return 0; } int ldepth,rdepth; ldepth=depth(root->lc); rdepth=depth(root->rc); if(ldepth>rdepth) { return ldepth+1; } else { return rdepth+1; }}int main(){ int n; scanf("%d",&n); while(n--) { scanf("%s %s",&mid,&last); len=strlen(last); t=0; struct node *root; root=creat(mid,last,len); fristput(root); t=depth(root); printf("%d\n",t); } return 0;}
0 0
- 数据结构已知中后序列求前序及深度
- 已知中序、后序 序列重构二叉树
- 已知后序与中序,求前序
- 已知中序和后序,求前序
- 数据结构与算法学习之二叉树的遍历:已知先序、中序、后序序列三者中的两种求另外一种遍历的算法
- 已知中序遍历及后序遍历结果求前序遍历
- 二叉树中,已知中序和后序序列,求先序序列
- 已知二叉树的中序序列和前序序列(或后序)求解树
- 已知后序遍历序列和中序序列遍历画出树
- 已知二叉树的中序序列和前序序列(或后序)求解树
- 已知中序遍历序列和后序遍历序列,求先序遍历
- 已知二叉树先序、中序(中序、后序)遍历序列,输出后序(先序)遍历序列
- 数据结构之已知二叉树前中序列求后序
- 二叉树已知先序序列(后序序列)、中序序列求解后序序列(先序序列)
- 【树】已知二叉树前序和中序遍历求后序遍历,及中序和后序遍历求前序遍历
- 二叉树系列(二):已知中序遍历序列和后序遍历序列,求先序遍历序列
- 已知二叉树的前序序列和中序序列,求二叉树的后序序列
- 已知二叉树的中序和前序序列(或后序)求解树
- GIT
- 【剑指offer】链表中的倒数第k个节点
- Java算法——求1到100累加的和,3种循环
- 数据库SQL优化大总结之 百万级数据库优化方案
- 设计模式面试题
- 数据结构已知中后序列求前序及深度
- jQuery Ajax用法详解
- 一维数组子数组的最大和
- 链表逆转和Fib队列(面试题)
- UCOSIII消息传递
- Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
- UVA 327-Evaluating Simple C Expressions
- multipart/form-data;application/x-www-form-urlencoded;text/plain;怎么接收
- Jstree的使用