Java—Determine whether a tree is a balanced binary tree
Idea : Starting from the root node, first determine whether the height difference between the left and right subtrees exceeds 1, and then determine whether the left and right subtrees are balanced binary trees
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;
}
}