• 数据结构实验三:二叉树及其应用


    设计两种输入模式建立一棵二叉树;输出该二叉树的深度;输出二叉树的子叶结点

    #include<stdio.h>
    #include<malloc.h>
    struct node{
        char data;
        struct node *lchild;
        struct node *rchild;
    };
    node * creat(node *p)
    {
        char ch;
        scanf("%c",&ch);
        if(ch==',')
            p=NULL;
        else
        {
            p=(node *)malloc(sizeof(node));
            p->data=ch;
            p->lchild=creat(p->lchild);
            p->rchild=creat(p->rchild);
        }
        return p;
    }

    void travel_zhongxu(node *p)
    {
        if(p!=NULL){
            travel_zhongxu(p->lchild);
            printf("%c",p->data);
        


        travel_zhongxu(p->rchild);
        }    
    }
    void travel_houxu(node *p)
    {
        if(p!=NULL){
            travel_houxu(p->lchild);
            travel_houxu(p->rchild);
            printf("%c",p->data);
        }    
    }
    void leaf(node *p,int &l)
    {
        if(p&&p->lchild==NULL&&p->rchild==NULL)
            l++;
        if(p!=NULL)
        {
            leaf(p->lchild,l);
            leaf(p->rchild,l);
        }
    }

    int deepth(node *p)
    {
        int d,dl,dr;
        if(!p)
            d=0;
        else{
            dl=deepth(p->lchild);
            dr=deepth(p->rchild);
            d=1+(dl>dr?dl:dr);
        }
        return d;
    }

    int main()
    {
        node *tree;
        tree=creat(tree);
        travel_zhongxu(tree);
        printf("\n");
        travel_houxu(tree);
        printf("\n");
        int l=0;
        leaf(tree,l);
        printf("%d\n",l);
        int deep;
        deep=deepth(tree);
        printf("%d\n",deep);
    }
  • 相关阅读:
    JNI编程基础
    C语言指针学习
    C语言字符串以及二维数组指针
    CPP数据类型本质以及变量本质分析
    junit在idea中的使用(2)--实践篇
    idea创建maven项目
    SourceTree的基本使用---团队开发/参与开源
    SourceTree的基本使用---基本介绍/本地开发
    流量分析系统---启动流程
    流量分析系统---redis
  • 原文地址:https://www.cnblogs.com/ma6174/p/2313316.html
Copyright © 2020-2023  润新知