pta ——还原二叉树

给定一棵二叉树的先序遍历序列和中序遍历序列,要求计算该二叉树的高度。

输入格式:

输入首先给出正整数N(≤50),为树中结点总数。下面两行先后给出先序和中序遍历序列,均是长度为N的不包含重复英文字母(区别大小写)的字符串。

输出格式:

输出为一个整数,即该二叉树的高度。

输入样例:

9
ABDFGHIEC
FDHGIBEAC

输出样例:

5

思路:
递归还原二叉树,主要是要理解递归大而化小的思想,把树的问题往左右子树上分。
类似的可以看看这道题:http://blog.csdn.net/vocaloid01/article/details/76033052

代码:

#include <stdio.h>

char Str1[55];
char Str2[55];

int Height(int t1,int t2,int lenth,int H){
    if(lenth == 0)return H-1;

    int len = 0;
    while(1){
        if(Str2[t2+len] == Str1[t1])break;
        len++;        /*注意这里len++必须放在判断后面,否则当lenth为1时会出问题*/ 
    }

    int h1 = Height(t1+1,t2,len,H+1);        /*返回左子树最大高度 */ 
    int h2 = Height(t1+len+1,t2+len+1,lenth-1-len,H+1);  /*返回右子树最大高度*/ 

    return h1 > h2 ? h1:h2;
}

int main(){
    int N;
    scanf("%d %s %s",&N,Str1,Str2);
    printf("%d",Height(0,0,N,1));
    return 0;
}
原文地址:https://www.cnblogs.com/vocaloid01/p/9514201.html