数据结构中树结构是非常重要的一种结构
下面给出求深度的代码
#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;
}