zoukankan      html  css  js  c++  java
  • 6-1 二叉树求深度和叶子数 (20 分)

    编写函数计算二叉树的深度以及叶子节点数。二叉树采用二叉链表存储结构

    函数接口定义:

    int GetDepthOfBiTree ( BiTree T);
    int LeafCount(BiTree T);
    

      

    其中 T是用户传入的参数,表示二叉树根节点的地址。函数须返回二叉树的深度(也称为高度)。

    裁判测试程序样例:

    //头文件包含
    #include<stdlib.h>
    #include<stdio.h>
    #include<malloc.h>
    
    //函数状态码定义
    #define TRUE       1
    #define FALSE      0
    #define OK         1
    #define ERROR      0
    #define OVERFLOW   -1
    #define INFEASIBLE -2
    #define NULL  0
    typedef int Status;
    
    //二叉链表存储结构定义
    typedef int TElemType;
    typedef struct BiTNode{
        TElemType data;
        struct BiTNode  *lchild, *rchild; 
    } BiTNode, *BiTree;
    
    //先序创建二叉树各结点
    Status CreateBiTree(BiTree &T){
       TElemType e;
       scanf("%d",&e);
       if(e==0)T=NULL;
       else{
         T=(BiTree)malloc(sizeof(BiTNode));
         if(!T)exit(OVERFLOW);
         T->data=e;
         CreateBiTree(T->lchild);
         CreateBiTree(T->rchild);
       }
       return OK;  
    }
    
    //下面是需要实现的函数的声明
    int GetDepthOfBiTree ( BiTree T);
    int LeafCount(BiTree T);
    //下面是主函数
    int main()
    {
       BiTree T;
       int depth, numberOfLeaves;
       CreateBiTree(T);
       depth= GetDepthOfBiTree(T);
    	 numberOfLeaves=LeafCount(T);
       printf("%d %d
    ",depth,numberOfLeaves);
    }
    
    /* 请在这里填写答案 */
    

      

    输入样例:

    1 3 0 0 5 7 0 0 0
    

      

    输出样例:

    3 2
    

      

    int GetDepthOfBiTree ( BiTree T)
    {
        if(T == NULL)
            return 0;
        else{
            int lenr = 1 + GetDepthOfBiTree(T->rchild);
            int lenl = 1 + GetDepthOfBiTree(T->lchild);
            if(lenr > lenl)
                return lenr;
            else
                return lenl;
        }
    }
    int LeafCount(BiTree T)
    {
        if( T == NULL)
            return 0;
        else if( T->lchild== NULL || T->rchild == NULL)
            return 1;
        else
            return LeafCount(T->lchild) + LeafCount(T->rchild);
    }
    

      

  • 相关阅读:
    VC字符串输出对齐问题(转)
    木马免杀全攻略(转)
    Windows Vista自动重启问题解决方法(转)
    图说VSS 6.0构架版本控制系统解决方案(转)
    几个有用的链接
    X64 Windows 2003 及XP 语言包官方下载
    .NET 3.5的版本问题(转)
    设计模式读书笔记工厂方法模式
    设计模式读书笔记装饰者模式
    设计模式读书笔记简单工厂模式
  • 原文地址:https://www.cnblogs.com/Jie-Fei/p/10151915.html
Copyright © 2011-2022 走看看