zoukankan      html  css  js  c++  java
  • [模板]二叉树的前、中、后序遍历

    二叉树是一个我们十分熟悉的一个数据结构

    但二叉树的题也没有多少,其中求前中后序遍历就是最经典的题了

    #include<iostream>
    #include<fstream>
    #define Data arr[pos].data
    #define Lson arr[pos].lson
    #define Rson arr[pos].rson
    using namespace std;
    struct edge
    {
        char data;
        int lson,rson;
    }arr[27];
    int n;
    void input();
    void Preorder(int);
    void Post_order(int);
    void Sequential(int);
    int main()
    {
        input();
        Preorder(1);
        printf("\n");
        Sequential(1);
        printf("\n");
        Post_order(1);
        return 0;
    }
    void input()
    {
        register int i;
        scanf("%d",&n);
        for(i=1;i<=n;i++){
            cin>>arr[i].data;
            scanf("%d%d",&arr[i].lson,&arr[i].rson);
        }
        return;
    }
    //前序遍历
    void Preorder(int pos)
    {
        printf("%c",Data);
        if(Lson)Preorder(Lson);
        if(Rson)Preorder(Rson);
        return;
    }
    //中序遍历 
    void Sequential(int pos)
    {
        if(Lson)Sequential(Lson);
        printf("%c",Data);
        if(Rson)Sequential(Rson);
        return;
    }
    //后序遍历 
    void Post_order(int pos)
    {
        if(Lson)Post_order(Lson);
        if(Rson)Post_order(Rson);
        printf("%c",Data);    
        return;
    }

    但实际上各个遍历就是换了个递归顺序而已,太水了

    博主是初中蒟蒻,能力弱,还请大家多多提出改进建议

  • 相关阅读:
    数据库存储语句
    数据库练习总结
    数据库练习
    数据库增添
    数据库创建
    cookie 和 session的区别 & 三种传值方式
    内置对象——cookie
    webform跨页面传值
    复合控件
    repeater(控件)数据展示
  • 原文地址:https://www.cnblogs.com/lihepei/p/10019900.html
Copyright © 2011-2022 走看看