H-Binary Tree Four of Data Structure Experiment: (First Order Middle Order) Restore Binary Tree

Description

Given the pre-order traversal sequence and the middle-order traversal sequence of a binary tree, it is required to calculate the height of the binary tree.
Input

There are multiple groups of input data. Enter 1 positive integer N (1 <= N <= 50) in the first line of each group of data, which is the total number of nodes in the tree, and the following 2 lines give the first and middle order traversal sequences, both of which are lengths A string of N that does not contain repeated English letters (case sensitive).

Output

Output an integer, which is the height of the binary tree.
Sample

Input

9
ABDFGHIEC
FDHGIBEAC
Output

5

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
/* 此题为二叉树部分遍历基础题,根据先序序列和中序序列来建立二叉树,
前序遍历序列的第一个节点就是根节点,并在中序序列中找到此节点,那么
中序序列的左边所有节点便是根节点的左子树部分,右边为右子树部分,因
此,可以用递归分而治之。*/
typedef struct node
{
    
    
    char data;
    struct node *lchild,*rchild;

}tree; //用typedef 为复杂的声明定义简单的别名,
      //即把结构体的名字给起名为 tree。
tree *creat(char *pre,char *in,int len)
{
    
    /* 每个子树的先序序列的第一个节点为子树的根,向后移动子树的中序序列
    ,依旧使用和上述方法一样的套路,找到中序序列中的根节点,便可分开
    得到左右子树,因此可以使用递归。*/
    tree  *root;
    if(len<=0)
    return NULL;//或者 root=NULL;
    root= new tree;// 和root = (tree *)malloc(sizeof(tree));一样;
    root->data=*pre;//此为把先序序列的第一个节点指定 为当前子树的根;
    char *p;//可理解为移动下标或者指针。
    for(p=in;p!=NULL;p++)
    {
    
    
        if(*p==*pre)
            break;
    }                 //这一步为在中序序列中查找到当前根节点。
    int lon=p-in;  //这就可以求出左子树节点的个数了;
    root->lchild=creat(pre+1,in,lon);//这个为创建左子树啊,递归,和参数里的意思一样。
    root->rchild=creat(pre+1+lon,p+1,len-lon-1);//这一块要充分理解,因为我们要的是创建右子树的
                                                //首地址,所以要计算好首地址所在的位置,以及剩余
                                                //的序列长度为右子树部分。
    return  root;//日,提交了两次都WA,原来忘了返回 。。。。。bitch。
}
int PostTreeDepth(tree *root )
{
    
     /*此为求二叉树深度的函数,递归定义如下:若根为空,则高度为0,若非空,就去求就好
    ,而且求高度是基于后序的思想,不能用前序和中序那样的格式去写,因为高度未知。*/
    int hl,hr,max;
    if(root!=NULL)
    {
    
    
        hl=PostTreeDepth(root->lchild);//求左子树高度;
        hr=PostTreeDepth(root->rchild);//求右子树高度;
        max = hl > hr ? hl : hr;
        return  max + 1; //最终二叉树的高度为左右子树中较大的深度加1;

    }
    else
        return 0;

}
int main()
{
    
    
    int n;
    tree *root;
    char s1[55],s2[55];
    while(~scanf("%d",&n))
    {
    
    
        scanf("%s",s1);
        scanf("%s",s2);
        //可以char *pre,*in;
        //让pre = s1;
        // in = s2;
        root=creat(s1,s2,n);
        printf("%d\n",PostTreeDepth(root));
    }
    return 0;
}

Guess you like

Origin blog.csdn.net/a675891/article/details/103963666