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; }
相关文章推荐
- 【逆向怎么玩】 动态调试一款牛逼C++ IDE实录
- C++求字符串第一次只出现一次的字符
- 字符串操作汇总 C/C++
- 《C++ Templates》(基础部分)笔记整理
- 可嵌套的C语言异常处理机制
- 单链表的c++实现,使用模板
- C语言异常处理——setjmp & longjmp
- 用c语言模拟c++的异常处理机制
- C语言中的异常处理
- C++的内置类型和用户自定义类型的互相转换
- 【Effective c++ 读书笔记】条款01 视 C++ 为一个语言联邦
- C++——try、throw、catch实例学习程序
- C++——windows结构异常转化成C++异常
- C++——STL中三种顺序容器的简要区别
- 【待思考】排序算法——快速排序
- C++——多态性实现机制
- C++ typedef用法小结
- C++杂七杂八
- C/C++——程序的内存分配
- 【学习笔记】【C语言】指针