zoukankan      html  css  js  c++  java
  • 7-1 根据后序和中序遍历输出先序遍历 (25 分)

    7-1 根据后序和中序遍历输出先序遍历 (25 分)

    本题要求根据给定的一棵二叉树的后序遍历和中序遍历结果,输出该树的先序遍历结果。

    输入格式:

    第一行给出正整数N(30),是树中结点的个数。随后两行,每行给出N个整数,分别对应后序遍历和中序遍历结果,数字间以空格分隔。题目保证输入正确对应一棵二叉树。

    输出格式:

    在一行中输出Preorder:以及该树的先序遍历结果。数字间有1个空格,行末不得有多余空格。

    输入样例:

    7
    2 3 1 5 7 6 4
    1 2 3 4 5 6 7
    

      

    输出样例:

    Preorder: 4 1 3 2 6 5 7
    

      

    #include<stdio.h>
    #include<stdlib.h>
    #include<malloc.h>
    typedef struct BiNode
    {
        int data;
        struct BiNode *lchild;
        struct BiNode *rchild;
    }BiNode, *BiTree;
    BiTree BuildPreTree(int *End, int *Mid, int n)//根据后序和中序构造二叉树
    {
        if(n <= 0)
            return NULL;
        int *p = Mid;
        while(*p != *(End+n-1))//后序的最后一个数是根节点,将p移动到中序的根节点位置,p就将中序分成左子树部分和右子树部分
              p++;
        BiTree T;
        T = (BiNode*)malloc(sizeof(BiNode));
        T->data = *p;
        int len_l = p - Mid;
        T->lchild = BuildPreTree(End, Mid, len_l);//找到左子树根节点,递归
        T->rchild = BuildPreTree(End+len_l, Mid+len_l+1, n-len_l-1);
        return T;
    }
    void CoutPre(BiTree T)//先序输出
    {
        if( T != NULL ){
            printf(" %d", T->data);
            CoutPre(T->lchild);
            CoutPre(T->rchild);
        }
    
    }
    int main()
    {
        int N, *End, *Mid;
        scanf("%d", &N);
        End = (int*)malloc(sizeof(int)*N);
        Mid = (int*)malloc(sizeof(int)*N);
        for(int i=0; i<N; i++)
            scanf("%d", &End[i]);
        for(int i=0; i<N; i++)
            scanf("%d", &Mid[i]);
        BiTree T = BuildPreTree(End, Mid, N);
        printf("Preorder:");
        CoutPre(T);
    }
    

      

  • 相关阅读:
    CSS Tab简洁版,切换标签
    浮动在网页右侧的简洁QQ在线客服
    Marquee 最简单图片滚动特效
    浮动的图片广告
    Button控件设置不能点击
    Android requires compiler compliance level 5.0 or 6.0. Found '1.4' instead的解决办法
    BroadcastReceiver组件
    发邮件 Async="true"
    ASP.NET GridView,DataList,Repeater日期格式显示
    Json原理和语法
  • 原文地址:https://www.cnblogs.com/Jie-Fei/p/10152148.html
Copyright © 2011-2022 走看看