C++求二叉树的最大高度差
生活随笔
收集整理的這篇文章主要介紹了
C++求二叉树的最大高度差
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
#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##7strcpy(s,"1##");t.Insert(s);t.Printf();cout << endl;cout << t.GetLength()<< endl;return 0;
}
總結
以上是生活随笔為你收集整理的C++求二叉树的最大高度差的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: libpng error: Not a
- 下一篇: 解决canvas画图模糊的问题