对于二叉树深度的计算

数据结构中树结构是非常重要的一种结构
下面给出求深度的代码

#include <iostream>
using namespace std;
 
 
template <class T>
struct tere
{
    T data;
    tere *l;
    tere *r;
};
template <class T>
class tee
{
    tere<T> *root;
    void preOrder(tere<T> *bt);
    void inOrder(tere<T> *bt);
    void Creat(tere<T> *&bt);
    int Deepth(tere<T> *bt);
public:
    tee()
    {
        root = NULL;
    }
    void preOrder()
    {
        preOrder(root);
 
    }
    void Creat()
    {
 
        Creat(root);
    }
    void inOrder(){ inOrder(root); }
    int Deepth(){ int i = Deepth(root); return i; }
};
 
 
 
template <class T>
void tee<T>::preOrder(tere<T> *bt)
{
    if (bt == NULL)
    {
        return;
    }
    cout << bt->data << " ";
    preOrder(bt->l);
    preOrder(bt->r);
}
 
 
template <class T>
void tee<T>::Creat(tere<T> *&bt)
{
 
    T ch;
    cin >> ch;
    if (ch == '#')
    {
        return;
    }
    bt = new tere<T>;
    bt->data = ch;
    bt->l = NULL;
    bt->r = NULL;
    Creat(bt->l);
    Creat(bt->r);
}
 
template <class T>
void tee<T>::inOrder(tere<T> *bt)
{
    if (bt == NULL)
    {
        return;
    }
 
    inOrder(bt->l);
    cout << bt->data << endl;
    inOrder(bt->r);
}
 
template <class T>
int tee<T>::Deepth(tere<T>* bt)
{
    if (bt == NULL)
    {
        return 0;
    }
    int nLeft = Deepth(bt->l);
    int nRight = Deepth(bt->r);
    return  nLeft>nRight ? nLeft + 1 : nRight + 1;
}
 
int main()
{
    tee<char> y;
    y.Creat();
    cout << y.Deepth() << endl;
    return 0;
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值