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("
    ");
    }
    选择了远方,便只顾风雨兼程
  • 相关阅读:
    SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder"
    Tomcat跨域
    Invalid bean definition with name 'dataSource' defined in class path resource [applicationContext.xml]
    网速测试
    程序员实用工具网站
    安装wls报(主清单位置 "/u01/app/oracle/inventory" 无效 (无法读取/写入/执行))
    pom.xml
    CUDA -- 内存分配
    最长上升子序列(LIS: Longest Increasing Subsequence)
    实例化渲染
  • 原文地址:https://www.cnblogs.com/ly-rabbit-wust/p/5575186.html
Copyright © 2011-2022 走看看