数据结构实验之二叉树八:(中序后序)求二叉树的深度
Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description
已知一颗二叉树的中序遍历序列和后序遍历序列,求二叉树的深度。
Input
输入数据有多组,输入T,代表有T组数据。每组数据包括两个长度小于50的字符串,第一个字符串表示二叉树的中序遍历,第二个表示二叉树的后序遍历。
Output
输出二叉树的深度。
Sample Input
2 dbgeafc dgebfca lnixu linux
Sample Output
4 3
Hint
Source
#include <stdio.h> #include<stdlib.h> #include <string.h> char mid[51] , hou[51]; typedef struct node { char data; struct node *left , *right; } tree; tree *creat(int n , char *mid , char *hou) { if (n == 0) return NULL; int i; tree *root; root = (tree *)malloc(sizeof(tree)); root ->data = hou[n-1]; for (i = 0 ; i < n ; i++) { if (hou[n-1] == mid[i]) { break; } } root->left = creat(i , mid , hou); root ->right = creat(n - i - 1 , mid + i + 1 , hou + i); return root; } int deeth(tree *root) { if (root == NULL) { return 0; } int maxl = deeth(root ->left) , maxr = deeth(root ->right); return maxl>maxr?1 + maxl:1+maxr ; } int main() { int t; tree *root; scanf("%d" , &t); while(t--) { int n; scanf("%s" , mid); scanf("%s" , hou); n = strlen(mid); root = (tree *)malloc(sizeof(tree)); root = creat(n , mid , hou); n = deeth(root); printf("%d\n" , n); } return 0; }