C++求二叉树的最大高度差

时间:2021-05-14 19:24:48
#include <iostream>
#include <string.h>
using namespace std; template<typename Type>
struct Node
{
Type data;
Node *left;
Node *right;
Node(Type d = Type()):data(d),left(NULL),right(NULL){}
//vs2013太变态了,一个空格出现未知文件尾出错,我找了10分钟。
}; template<typename Type>
class Tree
{
public:
Tree()
{
root = NULL;
flags = '#';
}
void Insert(const char *str)
{
Insert(root, str);
}
void Printf()
{
Printf(root);
}
int GetLength()//求最大高度差。
{
int i = GetLengthMax();
int j = GetLengthMin();
return i - j;
}
int GetLengthMax()
{
return GetLengthMax(root);
}
int GetLengthMin()
{
return GetLengthMin(root);
}
private:
int GetLengthMax(Node<Type> *t)
{
if (t == NULL)
return 0;
else
{
return GetLengthMax(t->left)>GetLengthMax(t->right)?GetLengthMax(t->left)+1:GetLengthMax(t->right) + 1;
}
}
int GetLengthMin(Node<Type>* t)
{
if (t == NULL)
return 0;
else
{
return GetLengthMin(t->left)<GetLengthMin(t->right) ? GetLengthMin(t->left) + 1 : GetLengthMin(t->right) + 1;
}
}
void Printf(Node<Type> *t)
{
if (t != NULL)
{
cout << t->data << " ";
Printf(t->left);
Printf(t->right);
}
}
void Insert(Node<Type> *&t, const char*& s)
{
if (*s == flags)
{
t = NULL;
return;
}
else
{
t = new Node<Type>(*s);
Insert(t->left,++s);
Insert(t->right,++s);
}
}
private:
Node<Type> *root;
char flags;
}; int main()
{
Tree<char> t;
char *s = new char[20];//1234####56##7
strcpy(s,"1##");
t.Insert(s);
t.Printf();
cout << endl;
cout << t.GetLength()<< endl;
return 0;
}