zoukankan      html  css  js  c++  java
  • 知道一棵二叉树的前序和中序序列求二叉树的后续序列

    解析:由二叉树的前序和中序序列,先构建出二叉树,然后再进行后续递归遍历

    注意递归停止的条件和相关的用法

    源代码如下:

    #include<iostream>
    using namespace std;
    
    //定义一个二叉树的数据结构
    typedef struct BiNode
    {
        char data;
        struct BiNode *lchild;
        struct BiNode *rchild;
    
    }BiNode,*BiTree;
    
    //后续递归遍历二叉树
    void laterOrder(BiTree & t)
    {
        if(t!=NULL)
        {
            
            laterOrder(t->lchild);    
            laterOrder(t->rchild);
            cout<<t->data;
            
        }
    }
    
    //递归构建二叉树
    void createBitree(BiTree &t,string presequence,string insequence)
    {
        //中序为空时 ,二叉树也为空 
        //右边中序和右边前序序列长度相同
        if(insequence.length()==0) 
        {
            t=NULL;
            return;
        }
        //每一次的根节点都由前序序列的第一个节点决定
        char rootNode=presequence[0];
        int index=insequence.find(rootNode);
        //左子书中序
        string lchild_insequence=insequence.substr(0,index);
        //右子树中序
        string rchild_insequence=insequence.substr(index+1);
        int lchile_length=lchild_insequence.length();
        int rchild_length=rchild_insequence.length();
        //左指数前序
        string lchild_presequence=presequence.substr(1,lchile_length);
        //右指数前序
        string rchild_presequece=presequence.substr(1+lchile_length);
        //构建当前遍历的当前子树根节点
        t=(BiTree)malloc(sizeof(BiNode));
        if(t!=NULL)
        {
            t->data=rootNode;
            createBitree(t->lchild,lchild_presequence,lchild_insequence);
            createBitree(t->rchild,rchild_presequece,rchild_insequence);
        }
    }
    
    
    
    void main()
    {
        BiTree t=NULL;
        string presequence="ABCDEFG";
        string insequence="CBEDAFG";
        createBitree(t,presequence,insequence);
        //后续遍历
        laterOrder(t);
        printf("
    ");
    }
    选择了远方,便只顾风雨兼程
  • 相关阅读:
    nodejs 不支持 typescript (...paramName:any[])剩余参数。变相支持方式。
    centos7安装nodejs
    .Net Core Linux centos7行—jenkins linux 构建.net core web app
    asp.net core 编译mvc,routing,security源代码进行本地调试
    发现一个很N且免费的html5拓扑图 关系图 生成组件
    Quill编辑器介绍及扩展
    vs2017 rc 离线安装包制作
    单体架构风格
    GlusterFS 安装 on centos7
    Expect 安装 on centos7
  • 原文地址:https://www.cnblogs.com/ly-rabbit-wust/p/5575186.html
Copyright © 2011-2022 走看看