• 二叉树


    复习下二叉树,创建二叉树,分别以先序,中序,后续三种遍历访问二叉树,输出二叉树的叶子节点及叶子节点的个数,并输出二叉树的高度

    #include<iostream> 
    #include<cstdio> 
    #include<cstring> 
    #include<cstdlib> 
    using namespace std; 
    typedef struct BiTNode 
    {    
        char data; 
        struct BiTNode *lchild,*rchild; 
    }BiTNode,*BiTree; 
    int Max(int x,int y) 

        return x>y?x:y; 

    void Create(BiTree &T)  //先序建一颗二叉树 

        char ch; 
        scanf("%c",&ch); 
        if(ch=='#') 
        T=NULL; 
        else 
        { 
            T=(BiTNode *)malloc(sizeof(BiTNode)); 
            T->data=ch; 
            Create(T->lchild); 
            Create(T->rchild); 
        } 

    void Preorder(BiTree &root)  //先序遍历打印二叉树 

        if(root!=NULL) 
        { 
            printf("%c ",root->data); 
            Preorder(root->lchild); 
            Preorder(root->rchild); 
        } 

    void Inorder(BiTree &root)  //中序遍历打印二叉树 

        if(root!=NULL) 
        { 
            Inorder(root->lchild); 
            printf("%c ",root->data); 
            Inorder(root->rchild); 
        } 

    void Postorder(BiTree &root)  //后续遍历打印二叉树 

        if(root!=NULL) 
        { 
            Postorder(root->lchild); 
            Postorder(root->rchild); 
            printf("%c ",root->data); 
        } 

    void Preorderleaf(BiTree &root) //先序遍历输出叶子节点 

        if(root!=NULL) 
        { 
            if(root->lchild==NULL&&root->rchild==NULL) 
            printf("%c ",root->data); 
            Preorderleaf(root->lchild); 
            Preorderleaf(root->rchild); 
        } 

    int LeafCount(BiTree &root)  //统计叶子节点的个数 

        int leaf; 
        if(root==NULL) 
        leaf=0; 
        else if(root->lchild==NULL&&root->rchild==NULL) 
        leaf=1; 
        else  
        leaf=LeafCount(root->lchild)+LeafCount(root->rchild); 
        return leaf; 

    int PostTreeDepth(BiTree &root)  //统计树的高度 

        int hl,hr,max; 
        if(root!=NULL) 
        { 
            hl=PostTreeDepth(root->lchild); 
            hr=PostTreeDepth(root->rchild); 
            max=Max(hl,hr); 
            return max+1; 
        } 
        else  
        return 0; 

    void dowork() 

        BiTree cam; 
        Create(cam); 
        Preorder(cam); 
        printf(" "); 
        Inorder(cam); 
        printf(" "); 
        Postorder(cam); 
        printf(" "); 
        printf("叶子节点:"); 
        Preorderleaf(cam); 
        printf(" "); 
        printf("叶子节点的个数为:%d ",LeafCount(cam)); 
        printf("树的深度为:%d ",PostTreeDepth(cam)); 

    int main() 

        dowork(); 
        return 0; 
    }

  • 相关阅读:
    [POI2014]KUR-Couriers
    [题解向] Luogu4092 [HEOI2016/TJOI2016]树
    [探究] OI中各种初级数论算法相关
    [SCOI2005]骑士精神
    [intoj#7]最短距离
    数列分块入门
    动态规划问题基础
    Luogu P1967 货车运输
    Luogu P3379 【模板】最近公共祖先(LCA)
    Luogu P3378 【模板】堆
  • 原文地址:https://www.cnblogs.com/milantgh/p/3690247.html
Copyright © 2020-2023  润新知