版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
Problem Description
已知一颗二叉树的中序遍历序列和后序遍历序列,求二叉树的深度。
Input
输入数据有多组,输入T,代表有T组数据。每组数据包括两个长度小于50的字符串,第一个字符串表示二叉树的中序遍历,第二个表示二叉树的后序遍历。
Output
输出二叉树的深度。
Sample Input
2
dbgeafc
dgebfca
lnixu
linux
Sample Output
4
3
Hint
Source
#include <stdio.h>
#include <string.h>
#define MaxTree 10
int i;
typedef struct Node
{
char data;
struct Node* lchild;
struct Node* rchild;
} TreeNode;
TreeNode* create_tree(int len, char* in, char* post)
{
TreeNode* root = NULL; // 初始化根结点
if (len > 0)
{
int len_l = 0, len_r = 0;
root = (TreeNode*)malloc(sizeof(TreeNode));
root->data = post+len-1; // 取后序序列的最后一个结点做参照并存入根结点
char* p;
for (p = in; p!= NULL; p++) // 遍历中序序列找到参照结点
{
if (*p == *(post+len-1))
break;
len_l++; // 累计左子树结点数
}
len_r = len - len_l-1; // 算出右子树结点数
root->lchild = create_tree(len_l, in, post); // 递归左右子树
root->rchild = create_tree(len_r, p+1, post+len_l);
}
return root;
}
int get_deep(TreeNode* root)
{
if (root == NULL) // 递归边界条件
{
return 0;
}
else
{
int left_deep = get_deep(root->lchild)+1;
int right_deep = get_deep(root->rchild)+1;
return left_deep > right_deep ? left_deep : right_deep;
}
}
int main()
{
int t;
TreeNode* root;
scanf("%d", &t);
while(t--)
{
char in[55];
char post[55];
scanf("%s %s", in, post);
root = create_tree(strlen(in), in, post);
int deep = get_deep(root);
printf("%d\n", deep);
}
return 0;
}