zoukankan      html  css  js  c++  java
  • SDUT 3343 数据结构实验之二叉树四:还原二叉树

    数据结构实验之二叉树四:还原二叉树

    Time Limit: 1000MS Memory Limit: 65536KB

    Problem Description

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

    Input

    输入数据有多组,每组数据第一行输入1个正整数N(1 <= N <= 50)为树中结点总数,随后2行先后给出先序和中序遍历序列,均是长度为N的不包含重复英文字母(区分大小写)的字符串。

     

    Output

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

    Example Input

    9 
    ABDFGHIEC
    FDHGIBEAC

    Example Output

    5

    DQE:

    本题为恢复二叉树,给出先序序列及中序序列,在二叉树的恢复问题中,已知先序和中序或者已知后序和中序即可恢复二叉树,原理为先序和后序可以获得根节点,从而分割中序序列得到左子树及右子树的中序序列,由此递归完成二叉树的恢复,本题采用指针+引用递归恢复,需对指针有一定的理解再阅读本代码。

     1 #include <iostream>
     2 #include <cstdio>
     3 
     4 using namespace std;
     5 
     6 struct Tree
     7 {
     8     char c;
     9     Tree *lt,*rt;
    10 };
    11 
    12 Tree *creat(char *&xx,char *zx)
    13 {
    14     if(*zx=='')
    15         return NULL;
    16     char *x,*y;
    17     Tree *r=new Tree;
    18     int i=0;
    19     while(zx[i]!='')
    20     {
    21         if(*xx==zx[i])
    22         {
    23             r->c=zx[i];
    24             zx[i]='';
    25             x=zx;
    26             y=zx+i+1;
    27             xx++;
    28             r->lt=creat(xx,x);
    29             r->rt=creat(xx,y);
    30             break;
    31         }
    32         i++;
    33     }
    34     return r;
    35 }
    36 
    37 int dev(Tree *r)
    38 {
    39     if(r==NULL)
    40         return 0;
    41     int l=dev(r->lt),rr=dev(r->rt);
    42     int m=l>rr?l:rr;
    43     return m+1;
    44 }
    45 
    46 int main()
    47 {
    48     char xx[55],zx[55],*p;
    49     Tree *root;
    50     int n;
    51     while(scanf("%d",&n)!=EOF)
    52     {
    53         scanf("%s%s",xx,zx);
    54         p=xx;
    55         root=creat(p,zx);
    56         printf("%d
    ",dev(root));
    57     }
    58     return 0;
    59 }
    60 
    61 /***************************************************
    62 User name: ***
    63 Result: Accepted
    64 Take time: 0ms
    65 Take Memory: 160KB
    66 Submit time: 2016-11-03 19:06:10
    67 ****************************************************/
  • 相关阅读:
    python---读取/写入excel用例数据
    unitest框架--认识与基本使用
    python--模拟蜂窝网(https)登陆总结
    python--实践--模拟浏览器(http)登陆
    python--return小练习
    python--smtp邮件使用
    关于商城价格变动对订单影响的问题
    history.back新页面跳转
    PHP无限极分类
    htaccess分布式配置文件常用写法
  • 原文地址:https://www.cnblogs.com/Leroscox/p/6031657.html
Copyright © 2011-2022 走看看