• 二叉树的建立与遍历


    不说废话了,直接上代码

    #include<iostream>
    #define MAXSIZE 100

    using namespace std;

    struct node
    {
        struct node *lchlid;
        struct node *rchlid;
        char date;
    };

    void BulidTree(struct node *&T)
    {
        char ch;
        cin>>ch;
        if(ch=='#')
            T=NULL;
        else
        {
            T = new struct node;//申请新的空间
            T->date=ch;
            BulidTree(T->lchlid);
            BulidTree(T->rchlid);
        }
    }

    void Preorder(struct node *&T)//先序遍历:访问根节点,先序遍历左子树,先序遍历右子树
    {
        if(T)
        {
            cout<<T->date<<" ";
            Preorder(T->lchlid);
            Preorder(T->rchlid);
        }
    }

    void Midorder(struct node *&T)//中序遍历:中序遍历左子树,访问根节点,中序遍历右子树
    {
        if(T)
        {
            Midorder(T->lchlid);
            cout<<T->date<<" ";
            Midorder(T->rchlid);
        }

    }

    void Postorder(struct node *&T)//后续遍历:后续遍历左子树,后续遍历右子树,访问根节点
    {
        if(T)
        {
            Midorder(T->lchlid);
            Midorder(T->rchlid);
            cout<<T->date<<" ";
        }
    }

    int main()
    {
        struct node *T;
        BulidTree(T);
        cout<<"Get Tree"<<endl;

        cout<<"Preorder"<<endl;
        Preorder(T);cout<<endl;

        cout<<"Midorder"<<endl;
        Midorder(T);cout<<endl;

        cout<<"Postorder"<<endl;
        Postorder(T);cout<<endl;

        return 0;
    }

  • 相关阅读:
    蓝桥杯 全球变暖(dfs)
    Bzoj3196 Tyvj 1730 二逼平衡树
    Bzoj3110 [Zjoi2013]K大数查询
    Bzoj4004 [JLOI2015]装备购买
    Bzoj2115 [Wc2011] Xor
    Bzoj1257 [CQOI2007]余数之和sum
    HDU1724 Ellipse
    Bzoj2178 圆的面积并
    SPOJ CIRU The area of the union of circles
    CodeForces 232E.Quick Tortoise
  • 原文地址:https://www.cnblogs.com/alan-W/p/6091023.html
Copyright © 2020-2023  润新知