建立一个二叉排序树,并计算其高度,是否为二叉平衡树

来源:互联网 发布:诗人 知乎 编辑:程序博客网 时间:2024/06/05 07:35
#include <iostream>  #include <cstdio>  using namespace std;struct Node{Node *lchild;Node *rchild;int d;}Tree[100];int loc;Node *create(){Tree[loc].lchild = Tree[loc].rchild = NULL;return &Tree[loc++];}Node *insert(Node *T, int x){if (T == NULL) {T = create();T->d = x;return T;}else if (T->d > x)T->lchild = insert(T->lchild, x);else if (T->d < x)T->rchild = insert(T->rchild, x);return T;}void get_he(Node *root, int &h){if (root == NULL)h = 0;else {int left_h;get_he(root->lchild, left_h);int right_h;get_he(root->rchild, right_h);if (left_h > right_h)h = 1 + left_h;elseh = 1 + right_h;}}int dep(Node *root)      //从底向上加{if (root == NULL)return 0;int l = 0, r = 0;l = dep(root->lchild);    //递归求左右深度r = dep(root->rchild);return l>r ? (l + 1) : (r + 1);  //深度为前一个左右最大值加1}bool bebalance(Node *root){if (root == NULL)return true;int ld = dep(root->lchild);int lr = dep(root->rchild);int di = abs(ld - lr);if (di>1)                 //根节点平衡return false;return bebalance(root->lchild) && bebalance(root->rchild);  //左右子树平衡}int main(){int n, x, i;loc = 0;Node *T = NULL;cin >> n;for (i = 0; i<n; i++) {cin >> x;T = insert(T, x);}int h = 0;get_he(T, h);cout << h << endl;cout << bebalance(T) << endl;system("pause");return 0;}

运行效果:


0 0
原创粉丝点击