# 数据结构 - 平衡二叉树（C++）

### 判断一棵二叉树是否平衡（C++）

/*
* Created by Chimomo
*/

#include <iostream>

#define NULL 0

using namespace std;

template<class T>
struct BTNode {
T data;
BTNode<T> *lChild, *rChild;

BTNode();

explicit BTNode(const T &val, BTNode<T> *childL = NULL, BTNode<T> *childR = NULL) {
data = val;
lChild = childL;
rChild = childR;
}

BTNode<T> *CopyTree() {
BTNode<T> *nl, *nr, *nn;
if (&data == NULL) {
return NULL;
}

nl = lChild->CopyTree();
nr = rChild->CopyTree();
nn = new BTNode<T>(data, nl, nr);

return nn;
}
};

template<class T>
BTNode<T>::BTNode() {
lChild = rChild = NULL;
}

template<class T>
class BinaryTree {
public:
BTNode<T> *root;

BinaryTree();

~BinaryTree();

void DestroyTree();

BTNode<T> *MakeTree(const T &element, BTNode<T> *l, BTNode<T> *r) {
root = new BTNode<T>(element, l, r);
if (root == NULL) {
cout << "Failed for applying storage address, system will close the process." << endl;
exit(1);
}

return root;
}

private:
void Destroy(BTNode<T> *&r);
};

template<class T>
BinaryTree<T>::BinaryTree() {
root = NULL;
}

template<class T>
BinaryTree<T>::~BinaryTree() {
DestroyTree();
}

template<class T>
void BinaryTree<T>::DestroyTree() {
Destroy(root);
}

template<class T>
void BinaryTree<T>::Destroy(BTNode<T> *&r) {
if (r != NULL) {
Destroy(r->lChild);
Destroy(r->rChild);
delete r;
r = NULL;
}
}

template<class T>
int isBalanced(BTNode<T> *r) {
if (!r) {
return 0;
}

int left = isBalanced(r->lChild);
int right = isBalanced(r->rChild);
if ((left >= 0) && (right >= 0) && ((left - right) <= 1) && ((left - right) >= -1)) {
return (left < right) ? (right + 1) : (left + 1);
} else {
return -1;
}
}

int main() {
BTNode<char> *b, *c, *d, *e, *f, *g;
BinaryTree<char> a;

b = a.MakeTree('F', NULL, NULL);
c = a.MakeTree('E', NULL, NULL);
d = a.MakeTree('D', b, NULL);
e = a.MakeTree('C', NULL, NULL);
f = a.MakeTree('B', d, c);
g = a.MakeTree('A', f, e);

if (isBalanced(a.root) >= 0) {
cout << "This IS a balanced binary tree." << endl;
} else {
cout << "This is NOT a balanced binary tree." << endl;
}

return 0;
}

// Output:
/*
This is NOT a balanced binary tree.

*/

11-20

05-06 1210
03-22 3478
07-22 1266
05-28 1374
10-21 7685
11-04 3549
08-07 223
06-19
07-25 488
07-10 5万+
11-06 180
10-31 3万+
06-14 3965
12-28 198
09-06 1万+
10-30 7896
©️2020 CSDN 皮肤主题: 书香水墨 设计师:CSDN官方博客