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("
    ");
    }
    选择了远方,便只顾风雨兼程
  • 相关阅读:
    LeetCode之“数学”:Plus One
    LeetCode之“动态规划”:Dungeon Game
    LeetCode之“排序”:Largest Number
    LeetCode之“字符串”:ZigZag Conversion
    LeetCode之“数组”:Rotate Array
    HTML 5 简介、视频、Video + DOM、音频、拖放
    HTML 多媒体、Object 元素、音频、视频
    HTML5 Canvas、内联 SVG、Canvas vs. SVG
    HTML5 语义元素、迁移、样式指南和代码约定
    HTML5 简介、浏览器支持、新元素
  • 原文地址:https://www.cnblogs.com/ly-rabbit-wust/p/5575186.html
Copyright © 2011-2022 走看看