How to judge whether a binary tree is a balanced binary tree

class Node{
    
    
    Integer data;
    Node left;
    Node right;

    public Node(int data) {
    
    
        this.data = data;
    }

    @Override
    public boolean equals(Object o) {
    
    
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Node node = (Node) o;
        return Objects.equals(data, node.data);
    }

    @Override
    public int hashCode() {
    
    
        return Objects.hash(data);
    }
}

class ReturnData{
    
    
    boolean isBalance;  //是否平衡
    int height; // 高度,即左右子树的最大高度+1

    public ReturnData(boolean isBalance, int height) {
    
    
        this.isBalance = isBalance;
        this.height = height;
    }
}
    /**
     * 是否是平衡二叉树
     * 判断:平衡二叉树的左右子树高度差不超过1,它的左右子树也是一颗平衡二叉树
     * @param root
     * @return
     */
    private static ReturnData isBalanceTree(Node root) {
    
    
        if(root == null){
    
    
            return new ReturnData(true, 0);
        }
        ReturnData leftData = isBalanceTree(root.left);
        ReturnData rightData = isBalanceTree(root.right);

        //左子树是否平衡 && 右子树是否平衡 && 左右子树的高度差是否平衡<=1
        return new ReturnData(leftData.isBalance && rightData.isBalance
                && Math.abs(leftData.height - rightData.height) <= 1, Math.max(leftData.height, rightData.height) + 1);
    }

Guess you like

Origin blog.csdn.net/Linging_24/article/details/128278536