• 知道一棵二叉树的前序和中序序列求二叉树的后续序列


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

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

    源代码如下:

    #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("
    ");
    }
    选择了远方,便只顾风雨兼程
  • 相关阅读:
    如何选择硅谷的IT公司
    NSDateFormatter设定日期格式
    内存映射文件
    double 转 int 的精度损失问题
    #ifndef #define 的用法
    How to improve the performance of MB5B
    Vendor Evaluation Questionair弹出空白页
    接受报价后创建合同,却无法弹出相应的合同类型
    SRM税务代码的决定逻辑
    How to improve the performance of MB51
  • 原文地址:https://www.cnblogs.com/ly-rabbit-wust/p/5575186.html
Copyright © 2020-2023  润新知