标签:输出 int restore ram blog 英文 字母 tom 还原
给定一棵二叉树的先序遍历序列和中序遍历序列,要求计算该二叉树的高度。
输入首先给出正整数N(≤50),为树中结点总数。下面两行先后给出先序和中序遍历序列,均是长度为N的不包含重复英文字母(区别大小写)的字符串。
输出为一个整数,即该二叉树的高度。
9
ABDFGHIEC
FDHGIBEAC
5
代码:
#include <stdio.h> #include <stdlib.h> char x[50],z[50]; typedef struct TreeNode *Tree; struct TreeNode { char data; Tree right,left; }; Tree CreatNode() { Tree p = (Tree)malloc(sizeof(struct TreeNode)); p -> left = p -> right = NULL; return p; } Tree RestoreTree(int x1,int x2,int z1,int z2) { Tree head = CreatNode(); head -> data = x[x1]; for(int i = z1;i <= z2;i ++) { if(z[i] == x[x1]) { if(i != z1)head -> left = RestoreTree(x1 + 1,x1 + i - z1,z1,i - 1); if(i != z2)head -> right = RestoreTree(x1 + i - z1 + 1,x2,i + 1,z2); break; } } return head; } int max(int a,int b) { if(a>b)return a; return b; } int Theight(Tree tree) { if(tree == NULL)return 0; return max(Theight(tree -> left),Theight(tree -> right))+1; } int main() { int n; scanf("%d",&n); scanf("%s%s",x,z); Tree head = RestoreTree(0,n-1,0,n-1); printf("%d",Theight(head)); }
标签:输出 int restore ram blog 英文 字母 tom 还原
原文地址:http://www.cnblogs.com/8023spz/p/7701244.html