二叉树的基本应用知识总结

 

#include <iostream>
using namespace std;
#include <malloc.h>
#include <stdio.h>
#define TURE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define IINFEASIBLE -1
#define OVERFLOW -2

#define MAX_TREE_SIZE 100//二叉树的最大结点数
typedef char ElemType;
typedef int Status;

typedef struct BiTNode{
    ElemType data;
    struct BiTNode *lchild,*rchild;//左右孩子指针
}BiTNode,*BiTree;//结点类型,指针类型

int count=0;//CountLeaf函数用到的全局变量
Status CreateBiTree(BiTree &T)//按照先序序列建立二叉树的二叉链表
{//按先序次序输入二叉树中结点的值(一个字符),#表示空树
 //构造二叉链表表示的二叉树T
    char ch;
    scanf("%c",&ch);
    if(ch=='#')
        T = NULL;//(出口)
    else
    {
        if(!(T = (BiTNode *)malloc(sizeof(BiTNode))))//要一个二叉树结点
            exit(OVERFLOW);
        T -> data = ch;//生成根结点
        CreateBiTree(T->lchild);//构造左子树
        CreateBiTree(T->rchild);//构造右子树
    }
    return OK;
}

Status InorderTraverse(BiTree T)//采用二叉链表存储结构,中序遍历二叉树
{
    if(T==NULL)
    {
        return ERROR;
    }
    else
    {
        InorderTraverse(T->lchild);//遍历左子树
        printf("%c",T->data);
        InorderTraverse(T->rchild);//遍历右子树
    }
    return OK;
}

int Depth(BiTree T)//求二叉树深度
{
    int depthval,depthleft,depthright;
    if(!T)
        depthval = 0;
    else
    {
        depthleft = Depth(T->lchild);//求左子树深度
        depthright = Depth(T->rchild);//求右子树深度
        depthval = 1 + (depthleft > depthright ? depthleft : depthright);
    }
    return depthval;
}

int CountLeaf(BiTree T)//需要在函数之前定义全局变量count
{
    if(T)
    {
        if((!T->lchild)&&(!T->rchild))
        {
            count++;
        }
        else
        {
            CountLeaf(T->lchild);
            CountLeaf(T->rchild);
        }
    }
    return count;
}

/*void CountLeaf(BiTree T,int &count)
{
    if(T)
    {
        if((!T->lchild)&&(!T->rchild))
            count++;
        CountLeaf(T->lchild,count);
        CountLeaf(T->rchild,count);
    }
}*/

int main()
{
    BiTree T ;
    cout << "请按照先序方式输入二叉树的结点元素;" << endl;
    CreateBiTree(T);
    cout << "创建成功的二叉树中序序列为;" <<endl;
    InorderTraverse(T);
    cout << endl<<"此二叉树的深度为:" <<Depth(T)<<endl;
    cout << "此二叉树的叶子结点个数为:" <<CountLeaf(T)<<endl;
    /*cout<<count<<endl;*/
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值