• 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 ****************************************************/
  • 相关阅读:
    LeetCode_167. Two Sum II
    LeetCode_160. Intersection of Two Linked Lists
    LeetCode_155. Min Stack
    LeetCode_141. Linked List Cycle
    LeetCode_136. Single Number
    LeetCode_125. Valid Palindrome
    HTML解析类 ,让你不使用正则也能轻松获取HTML相关元素 -C# .NET
    .net 根据匿名类生成实体类,根据datatable生成实体类,根据sql生成实体类
    将form表单元素转为实体对象 或集合 -ASP.NET C#
    ASP.NET 图片上传工具类 upload image简单好用功能齐全
  • 原文地址:https://www.cnblogs.com/Leroscox/p/6031657.html
Copyright © 2020-2023  润新知