• 7-23 还原二叉树(25 分)


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

    输入格式:

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

    输出格式:

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

    输入样例:

    9
    ABDFGHIEC
    FDHGIBEAC
    

    输出样例:

    5
    解题思路:先序中第一个字母A为根节点,因而中序的第一个字母到A为A的左子树,A以后的字母为A的右子树,递归可建二叉树
     1 #include<stdio.h>
     2 #include<stdlib.h>
     3 #include<string.h>
     4 
     5 typedef struct TNode
     6 {
     7     char data;
     8     struct TNode *lchild,*rchild;
     9 } TNode,*Tree;
    10 
    11 Tree CreatTree( char xian[],char zhong[],int n);
    12 int High( Tree t);
    13 
    14 char xian[55];   //先序序列
    15 char zhong[55];  //中序序列
    16 int n;
    17 
    18 int main()
    19 {
    20     scanf("%d",&n);
    21     scanf("%s",xian);
    22     scanf("%s",zhong);
    23     Tree tree = CreatTree( xian,zhong,n);
    24     printf("%d",High(tree));
    25     return 0;
    26 }
    27 
    28 Tree CreatTree( char xian[],char zhong[],int n)
    29 {
    30     if( n==0 ) return NULL;
    31     int index = 0;
    32     Tree temp = (Tree) malloc(sizeof(struct TNode));
    33 
    34     while( index < n)
    35     {
    36         if( zhong[index]==xian[0]) break;
    37         index ++;
    38     }
    39     temp->data = xian[0];
    40     temp->lchild = CreatTree(xian+1,zhong,index);
    41     temp->rchild = CreatTree(xian+1+index,zhong+index+1,n-index-1);
    42     return temp;
    43 }
    44 
    45 int High( Tree t)
    46 {
    47     if( !t ) return 0;
    48     int lh = High(t->lchild);
    49     int rh = High(t->rchild);
    50     if( lh>rh ) return ++lh;
    51     else return ++rh;
    52 }





    在这个国度中,必须不停地奔跑,才能使你保持在原地。如果想要寻求突破,就要以两倍现在速度奔跑!
  • 相关阅读:
    4个常用的HTTP安全头部
    Content Security Policy 入门教程
    前端安全配置之Content-Security-Policy(csp)
    关于setConnectTimeout和setReadTimeout的问题
    Maven库下载很慢解决办法,利用中央仓库
    ibatis Order By注入问题
    Web系统常见安全漏洞及解决方案-SQL盲注
    玩得一手好注入之order by排序篇
    python接口自动化29-requests-html支持JavaScript渲染页面
    python接口自动化28-requests-html爬虫框架
  • 原文地址:https://www.cnblogs.com/yuxiaoba/p/8406899.html
Copyright © 2020-2023  润新知