Java - Détermine si un arbre est un arbre binaire équilibré
Idée : à partir du nœud racine, déterminez d'abord si la différence de hauteur entre les sous-arbres gauche et droit dépasse 1, puis déterminez si les sous-arbres gauche et droit sont des arbres binaires équilibrés
Code:
/**
* @Author shall潇
* @Date 2021/3/4
* @Description 平衡二叉树就是左子树和右子树的高度差不能超过1,且左右子树必须是平衡二叉树
*
*/
public class BinaryBalanceTree {
public boolean isBalancedTree(Node root){//判断左右子树是否为平衡二叉树
if(root==null)return true;
if(Math.abs(getDepth(root.left)-getDepth(root.right))<=1){ //如果左右子树高度相差在1以及以内,则是
return isBalancedTree(root.right) && isBalancedTree(root.right);
}else {
return false;
}
}
public int getDepth(Node root){
if(root==null)return 0;
int left = getDepth(root.left); //获取左子树高度
int right = getDepth(root.right); //获取右子树高度
return (left>right?left:right)+1;
}
class Node{ //创建二叉树的数据结构
int date;
Node left;
Node right;
}
}