求二叉树的深度
Time Limit: 1000MS Memory limit: 65536K
题目描述
已知一颗二叉树的中序遍历序列和后序遍历序列,求二叉树的深度。
输入
输入数据有多组,输入T组数据。每组数据包括两个长度小于<font face="\"Times" new="" roman,="" serif\"="" style="padding: 0px; margin: 0px;">50的字符串,第一个字符串表示二叉树的中序遍历,第二个表示二叉树的后序遍历。
输出
输出二叉树的深度。
示例输入
2 dbgeafc dgebfca lnixu linux
示例输出
4 3
提示
给出二叉树的中序和后序, 求深度, 和给出前序和中序求高度差不多,只是改一下建立左右子树的顺序就好了
来源
示例程序
#include <bits/stdc++.h>
using namespace std;
struct node
{
char data;
node *lchild, *rchild;
}*root;
char str1[75], str2[75];
int Max, k, l;
node *creat()
{
node *root;
root = new node;
root->lchild = NULL;
root->rchild = NULL;
return root;
}
node *build(int low, int high)
{
int flag;
if(low > high)
return NULL;
for(int i = low; i <= high; i++)
{
if(str2[k] == str1[i])
{
flag = i;
break;
}
}
k--;
node *root;
root = creat();
root->data = str1[flag];
root->rchild = build(flag+1, high);//<span style="color: rgb(0, 130, 0); font-family: Consolas, 'Courier New', Courier, mono, serif; line-height: 18px; background-color: rgb(245, 250, 226);">根节点右侧flag到high为整棵树右子树</span>
root->lchild = build(low, flag-1);//low到flag为左子树;
return root;
}
void depth(node *root, int ans)
{
if(root)
{
if(Max < ans)
Max = ans;
depth(root->lchild, ans+1);
depth(root->rchild, ans+1);
}
}
int main()
{
int n;
cin >> n;
while(n--)
{
cin >> str1;
cin >> str2;
l = strlen(str1);
k = l-1;
root = build(0, l-1);
Max = 0;
depth(root, 1);
cout << Max << endl;
}
}