判断一颗二叉树是不是平衡AVL

#include <stdio.h>
#include <cmath>


//二叉树结点
typedef struct binary_tree_node_t{
	binary_tree_node_t * left;
	binary_tree_node_t * right;
	int  elem;

};

//方法1:
//按照后序遍历的顺序,判断左右子树,同时得到左右子树的深度;再检查当前结点的左右子树深度差是否不大于1
bool isBalanced(binary_tree_node_t * root, int * depth){//传参一个int指针,可直接修改一个int值
	if(root == NULL){
		*depth = 0;
		return true;
	}

	int leftDepth, rightDepth;

	if(isBalanced(root->left, &leftDepth) && isBalanced(root->right, &rightDepth)){
		if( abs(leftDepth - rightDepth) <= 1){

			*depth = leftDepth > rightDepth ? leftDepth+1 : rightDepth+1;//同时求出当前结点的深度!!!
			return true;
		}
	}

	return false;
}

//方法2:
//求子树的最大深度和最小深度之差
int maxDepth(binary_tree_node_t * root){
	if(root == NULL){
		return 0;
	}
	return maxDepth(root->left) > maxDepth(root->right) ?  maxDepth(root->left)+1 : maxDepth(root->right)+1;
}

int minDepth(binary_tree_node_t * root){
	if(root == NULL){
		return 0;
	}
	return minDepth(root->left) < minDepth(root->right) ?  minDepth(root->left)+1 : minDepth(root->right)+1;
}


bool isBalanced2(binary_tree_node_t * root){
	int diff = abs(maxDepth(root) - minDepth(root));

	return diff<=1;
}



//判断一颗二叉树是不是平衡二叉树
int main(){
	binary_tree_node_t ns[10];

	for(int i = 1; i <= 7; i++){
		binary_tree_node_t tmp;	
		tmp.elem  = i;
		tmp.left = NULL;//必须显式初始化为NULL
		tmp.right = NULL;
		ns[i] = tmp;
	}
	
	binary_tree_node_t root;
	root.left = NULL;
	root.right = NULL;
	root.elem = 4;

	root.left = &ns[2];
	root.right = &ns[5];

	ns[2].left = &ns[1];
	ns[2].right = &ns[3];
	 
	ns[5].right = &ns[6];


	int depth = 0;
	
	printf("%d\n",isBalanced(&root, &depth)?1:0);
	//printf("%d\n",isBalanced2(&root)?1:0);

	return 0;
}


转载于:https://my.oschina.net/kaneiqi/blog/308872

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值