数据结构——二叉树(2)

这一篇写一下(1)求二叉树高度

                        (2)求叶子节点数

                        (3)层次遍历

这是上一篇博文,关于递归/非递归先中后序遍历二叉树

http://blog.csdn.net/dala_da/article/details/79234619

#include<iostream>
#include<stdlib.h>
#include<queue>

using namespace std;

typedef struct BiTNode{
    char data;
    BiTNode *lchild, *rchild;
}BiTNode, *BiTree;

void Input_BiTree(BiTree &exa){
    char data;
    cin>>data;
    if(data=='#'){
        exa=NULL;
        return;
    }
    else{
        exa=(BiTree)malloc(sizeof(BiTNode));
        exa->data=data;
        Input_BiTree(exa->lchild);
        Input_BiTree(exa->rchild);
    }
}

int GetDepth(BiTree exa){
    BiTree T=exa;
    if(T==NULL)
        return 0;
    else{
        int depth_rchild=GetDepth(T->lchild);    //该节点左子树深度
        int depth_lchild=GetDepth(T->rchild);    //该节点右子树深度
        int depth = depth_rchild>depth_lchild ? depth_rchild : depth_lchild;
        return ++depth;
    }
}

int GetLeafNodeCount(BiTree exa){
    BiTree T=exa;
    if(T==NULL)
        return 0;
    else if(T!=NULL && T->rchild==NULL && T->lchild==NULL) //说明是叶子节点,返回1
        return 1;
    else
        return GetLeafNodeCount(T->lchild)+GetLeafNodeCount(T->rchild);
}

void LevelOrder(BiTree exa){
    BiTree root=exa;
    BiTree LevelFirst, LevelEnd;  //分别表示每一层的最左面节点和最右面节点
    queue<BiTree> p;

    p.push(root);
    LevelFirst=LevelEnd=p.front();

    while(1){
        while(LevelFirst<=LevelEnd){
            if(LevelFirst->lchild!=NULL)  //不为空则压入队列。由于队列先进先出的性质,低层节点肯定比高层节点先pop出来
                p.push(LevelFirst->lchild);
            if(LevelFirst->rchild!=NULL)
                p.push(LevelFirst->rchild);
            cout<<LevelFirst->data<<" ";
            p.pop();
            if(p.empty())    //上一步pop完成后,有可能遍历完最后一个节点,则此时queue为空,层次遍历结束
                return;
            LevelFirst=p.front();
        }
        LevelEnd=p.back();
    }
}

int main(){

    BiTree T;
    int depth, LeafNodeCount;

    cout<<"请输入二叉树(按照先序)"<<endl;
    Input_BiTree(T);

    depth=GetDepth(T);
    cout<<"depth="<<depth<<endl;

    LeafNodeCount=GetLeafNodeCount(T);
    cout<<"LeafNodeCount="<<LeafNodeCount<<endl;

    cout<<"层次遍历为:"<<endl;
    LevelOrder(T);

    return 0;
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值