【数据结构】给定一棵二叉搜索树,判断其是否AVL树

分析

因为给出的是二叉搜索树,所以只要判断平衡因子是否为1就可以

Java版本实现

//获取树的深度
	int getDepth(Node<T> root , int initDeep){
		if(root == null)
			return initDeep;
		int leftDeep = initDeep;
		int rightDeep = initDeep;
		if(root.getLeft() != null)
			leftDeep = getDepth(root.getLeft() , initDeep++);
		if(root.getRight() != null)
			rightDeep = getDepth(root.getRight(), initDeep++);
		
		return leftDeep > rightDeep ? leftDeep : rightDeep; 
	}
	
	//判断树是否失去平衡
	boolean unBanlace(Node<T> root) {
		if(root == null)
			return false;
		int leftHeight = getDepth(root.getLeft(), 1);
		int rightHeight = getDepth(root.getRight(), 1);
		return Math.abs(leftHeight - rightHeight) > 1;
	}//判断是否AVL树
 	boolean isAVL() {
//		if(root == null)
//			return false;
//		int left = getDepth(root.getLeft(), 1);
//		int right = getDepth(root.getRight(), 1);
//		if(Math.abs(left - right) > 1)
//			return false;
//		return true;
 		return unBanlace(root) == false;
	}
	
	
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值