求二叉树的叶子节点数目/二叉树的高度

#include<iostream>
#include<stdlib.h>
#include<stdio.h>
#define MAXSIZE 100
using namespace std;
struct bitree{
    char data;
    struct bitree * lchild , *rchild ;
};
//先序创建二叉树
struct bitree * createbitree(){
        char  c ;
        struct bitree *root ;
        scanf("%c" , &c) ;
        if(c == '#')
            root = NULL ;
        else{

            root = (struct bitree *)malloc(sizeof(struct bitree) ) ;
            root->data = c ;
            root->lchild = createbitree() ;
            root->rchild = createbitree() ;
        }
        return root ;
}
//前序遍历二叉树
void preorder(struct bitree *root){
    if(root != NULL){
        printf("%c\n" , root->data) ;
        cout <<"root = " << root << endl;
        preorder(root->lchild) ;
        preorder(root->rchild) ;
    }
}
//前序遍历来查找结点x的运算
//此算法有问题,因为无论如何算法都是完全遍历整个二叉树,就算找到了结点x,也无法返回结点x地址
//struct bitree* bisearch(struct bitree *root , char x){
//    if(root == NULL)
//        return NULL ;
//    if(root->data == x){
//        cout<<"return root = " << root << endl;
//        return root ;
//    }
//    bisearch(root->lchild , x) ;
//    bisearch(root->rchild , x) ;
//}

//求二叉树中的叶子节点数目,书上说是中序遍历,我认为是后序遍历
int countleaf(struct bitree * root){
    if(root == NULL)
        return 0 ;
    int num = 0 , num1 , num2;
    if(root ->lchild == NULL && root ->rchild == NULL)
        num++ ;
    else{
//        num1 = countleaf(root->lchild) ;
//        num2 = countleaf(root->rchild) ;
//        num = num1 + num2 ;
        num = countleaf(root->lchild) + countleaf(root->rchild) ;
    }
    return num ;
}
//后序遍历求二叉树的高度(节点的最大层数(层数从1开始))
int treedepth(struct bitree * root){
    if(root == NULL)
        return 0 ;
    int h , lh , rh ;
    lh = treedepth(root->lchild) ;
    rh = treedepth(root->rchild) ;
    if(lh >= rh)
        h = lh +1 ;
    else
        h = rh+1 ;
    return h ;
}
int main(){
   struct bitree * root , *temp;
   root = createbitree() ;
   cout<<"前序遍历二叉树"<<endl;
   preorder(root) ;
//   cout<<"查找元素x"<< endl;
//   temp = bisearch(root , 'D') ;
//   cout<<"temp = " << temp << endl;
//   if(temp == NULL)
//    cout<<"无此元素" << endl;
//   else
//    cout<<"查找的元素为 :"<< temp->data <<  endl;
    cout<<"二叉树的叶子节点数目" << endl;
    int num = countleaf(root ) ;
    cout<<"叶子节点数目 = " << num << endl;
    cout<<"求二叉树的高度" << endl;
    int depth = treedepth(root) ;
    cout<<"二叉树高度 = " << depth << endl;
   return 0 ;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值