zoukankan      html  css  js  c++  java
  • 数据结构实验--还原二叉树

    一、问题描述

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

     

    二、输入/输出

    输入说明:输入正整数N,为树中结点总数。另外给出先序遍历序列和中序遍历序列。

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

     

    三、代码
     
     1 # include <stdio.h>
     2 # include <malloc.h>
     3 
     4 typedef struct tagNode
     5 {
     6     char data;
     7     struct tagNode *left;//左孩子
     8     struct tagNode *right;//右孩子
     9 }BitTree;
    10 
    11 BitTree * PreIn(char *pre, char *in, int n)
    12 {
    13 
    14     int i = 0;
    15     BitTree *BT = NULL;
    16     BitTree *left = NULL;
    17     BitTree *right = NULL;
    18     if(n == 0) return NULL;
    19 
    20     BT = (BitTree*)malloc(sizeof(BitTree));
    21     BT->data = pre[0];
    22 
    23     for(i = 0; i < n; i++)
    24     {
    25         if(pre[0] == in[i])
    26             break;
    27     }
    28 
    29     left = PreIn(pre+1, in, i);
    30     right = PreIn(pre+i+1, in+i+1, n-i-1);
    31 
    32     BT->left = left;
    33     BT->right = right;
    34 
    35     return BT;
    36 }
    37 
    38 int GetBitTreeHight(BitTree *BT)
    39 {
    40     int HL, HR, MaxH;
    41     if(BT)
    42     {
    43         HL = GetBitTreeHight(BT->left);
    44         HR = GetBitTreeHight(BT->right);
    45 
    46         MaxH = HL > HR?HL : HR;
    47 
    48         return MaxH + 1;
    49     }
    50 
    51     else
    52     {
    53         return 0;
    54     }
    55 }
    56 int main()
    57 {
    58     int size;
    59     int h;
    60     char pre[50];
    61     char in[50];
    62     BitTree * BT;
    63     printf("请输入结点个数:");
    64     scanf("%d",&size);
    65     printf("
    请输入先序序列
    ");
    66     scanf("%s", pre);
    67     printf("
    请输入中序序列
    ");
    68     scanf("%s", in);
    69 
    70     BT = PreIn(pre, in, size);
    71 
    72     h = GetBitTreeHight(BT);
    73     printf("二叉树高度为%d", h);
    74     return 0;
    75 
    76 
    77 }
    View Code

    参考:http://blog.csdn.net/cwqbuptcwqbupt/article/details/6874622

  • 相关阅读:
    CodeForces 659F Polycarp and Hay
    CodeForces 713C Sonya and Problem Wihtout a Legend
    CodeForces 712D Memory and Scores
    CodeForces 689E Mike and Geometry Problem
    CodeForces 675D Tree Construction
    CodeForces 671A Recycling Bottles
    CodeForces 667C Reberland Linguistics
    CodeForces 672D Robin Hood
    CodeForces 675E Trains and Statistic
    CodeForces 676D Theseus and labyrinth
  • 原文地址:https://www.cnblogs.com/icez/p/3397805.html
Copyright © 2011-2022 走看看