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

#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;
		else
			h = 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;
}

运行效果:

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

    原文作者:平衡二叉树
    原文地址: https://blog.csdn.net/u010951938/article/details/41957849
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞