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);
    }
    

      

  • 相关阅读:
    pch文件配置出现 Expected unqualified-id 和 Unkown type name 'NSString'
    App Store Connect Operation Error ERROR ITMS-90032: "Invalid Image Path
    Xcode面板的使用
    KVO的使用
    苹果开发者账号注册-您在注册时提供的地址无效或者不完整
    Apple导出p12证书 导出证书为p12 Apple开发
    iOS开发-导出profile文件
    App Store提交审核报错 ERROR ITMS-90087解决办法
    Win10 的操作中心如果不见了
    什么时候调用dealloc
  • 原文地址:https://www.cnblogs.com/Jie-Fei/p/10152148.html
Copyright © 2011-2022 走看看