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("
    ");
    }
    选择了远方,便只顾风雨兼程
  • 相关阅读:
    《页面优化》-- 一个大话题,也是一个面试比较老俗的问题
    Single-SPA 前端微服务化 动态路由多系统合并
    浏览器的DNS缓存查看和清除
    es6 的类 class
    数据驱动表格| 根据json数据,自动生成合并式table
    隐式调用 以及使用技巧
    柯里化currying + 隐式调用 = 一个有名的add面试题
    工作笔记
    php升级版本
    git使用
  • 原文地址:https://www.cnblogs.com/ly-rabbit-wust/p/5575186.html
Copyright © 2011-2022 走看看