数据结构之统计二叉树的结点,叶子,深度

#include <iostream>

using namespace std;

struct BitNode
{
    char data;
    BitNode *lchild;
    BitNode *rchild;
};

void create(BitNode *&T)
{
    char ch;
    cin>>ch;
    if(ch=='#')
        T=NULL;
    else
    {
        T=new BitNode;
        T->data=ch;
        create(T->lchild);
        create(T->rchild);
    }
}

void preOrder(BitNode *T)
{
    if(T)
    {
        cout<<T->data<<endl;
        preOrder(T->lchild);
        preOrder(T->rchild);        
    }
}

bool isEmpty(BitNode *T)
{
    return T==NULL;
}

int nodeCount(BitNode *T)    //结点数
{
    if(T)
        return nodeCount(T->lchild)+nodeCount(T->rchild)+1;
    return 0;
}

int leafCount(BitNode *T)    //叶子数
{
    if(T==NULL)
        return 0;
    if(T->lchild==NULL &&T->rchild==NULL)
        return 1;
    return leafCount(T->lchild)+leafCount(T->rchild);
}

int oneDegree(BitNode *T)    //度为1的结点个数
{
    if(T==NULL)
        return 0;
    int n=nodeCount(T);
    int m=leafCount(T);
    return n-m-m+1;
}

int twoDegree(BitNode *T)    //度为2的结点个数
{
    if(T==NULL)
        return 0;
    int    n=leafCount(T);
    return n-1;
}

inline int max(int x,int y)
{
    return (x>y)?x:y;
}

int depth(BitNode *T)    //深度
{
    if(T==NULL)
        return 0;
    return max(depth(T->lchild),depth(T->rchild))+1;
}

int main()
{
    BitNode *T;
    create(T);
    preOrder(T);
    cout<<"nodeCount="<<nodeCount(T)<<endl;
    cout<<"leafCount="<<leafCount(T)<<endl;
    cout<<"oneDegree="<<oneDegree(T)<<endl;
    cout<<"twoDegree="<<twoDegree(T)<<endl;
    cout<<"depth="<<depth(T)<<endl;

    return 0;
}

猜你喜欢

转载自blog.csdn.net/wrc_nb/article/details/80273501
今日推荐