您的位置:首页 > 编程语言 > C语言/C++

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

2015-06-25 08:09 411 查看
#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: