zoukankan      html  css  js  c++  java
  • 二叉树的前序中序转后序,二叉树的后序中序转层序。

    1、二叉树的前序中序转后序:

    先通过前序中序建树,再进行后序遍历。

    (1)建树:每次记录先序遍历的根,中序遍历的范围;

    先找到根在中序遍历中的位置,然后找到左子树,右子树;

    分别找到左子树的根和范围与右子树的根和范围。

    递归下去,直到st>ed.

    (2)后序遍历;

    #include<iostream>
    #include<cstdio>
    #include<vector>
    #include<cstring>
    #include<cstdlib>
    using namespace std;
    vector <int> level(10000,-1);
    struct Node{
        int data;
        struct Node *Left,*Right;
    };
    typedef struct Node* Tree;
    Tree T;
    int pre[1000],in[1000],n;
    Tree f(int root,int st,int ed)
    {
        int i,d;
        if(st>ed) return NULL;
        Tree tp=(Tree)malloc(sizeof(struct Node));
        tp->data=pre[root];
        for(i=st;i!=ed;i++) if(pre[root]==in[i]) break;
        tp->Left=f(root+1,st,i-1);
        tp->Right=f(root+(i-st)+1,i+1,ed);
        return tp;
    }
    void Print(Tree T)
    {
        if(T!=NULL)
        {
            Print(T->Left);
            Print(T->Right);
            printf("%d ",T->data);
        }
    }
    int main(void)
    {
        int i,j;
        scanf("%d",&n);
        for(i=0;i<n;i++) scanf("%d",&pre[i]);
        for(i=0;i<n;i++) scanf("%d",&in[i]);
        Tree T=f(0,0,n-1);
        Print(T);
        return 0;
    } 
    
    /*
    7
    1 2 4 5 3 6 7
    4 2 5 1 6 3 7
    */
    View Code

    2、二叉树的后序中序转层序:

    有两种思路:

    (1)建树,再遍历,与1的方法相同。

    (2)直接用数组记录二叉树,然后输出数组。

    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<vector>
    using namespace std;
    vector <int> level(10000,-1);
    int post[10000],in[10000];
    void f(int root,int st,int ed,int pos)
    {
        int i,d;
        if(st>ed) return ;
        level[pos]=post[root];
        for(i=st;i!=ed;i++) if(post[root]==in[i]) break;
        f(root-(ed-i)-1,st,i-1,pos*2);
        f(root-1,i+1,ed,pos*2+1);
    }
    int main(void)
    {
        int n,i,j;
        scanf("%d",&n);
        for(i=0;i<n;i++) scanf("%d",&post[i]);
        for(i=0;i<n;i++) scanf("%d",&in[i]);
        f(n-1,0,n-1,1);
        for(i=1,j=0;i<level.size();i++)
        {
            if(level[i]!=-1)
            {
                if(j) printf(" ");
                printf("%d",level[i]);
                j++;
            }
        }
        return 0;
    }
    View Code
  • 相关阅读:
    Linux基本知识
    Linux 基金会发起开源创新计划,为全球对抗 COVID-19 提供基础架构
    单片机程序设计有十层功力,你现在在哪一层?
    C语言太复杂?CUDA Python也能实现并行计算加速!
    Java 基础 子类赋值给父类问题
    SpringBlade AVUE 拖拽排序
    java 基础 Long类型 判断是否相等
    数字量输入模块和模拟量输入模块的区别是什么?
    模拟量输入模块和模拟量输出模块的应用范围
    NB-IOT关键技术分析
  • 原文地址:https://www.cnblogs.com/2018zxy/p/10073244.html
Copyright © 2011-2022 走看看