坚持刷题 | 平衡二叉树-代码实现

时间:2024-01-27 07:02:42
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int x) {
        val = x;
    }
}

public class BinaryTreeBalance {

    public boolean isBalanced(TreeNode root) {
        if (root == null) {
            return true;
        }

        int leftHeight = getHeight(root.left);
        int rightHeight = getHeight(root.right);

        // 检查当前节点是否平衡,并递归检查左右子树
        return Math.abs(leftHeight - rightHeight) <= 1
                && isBalanced(root.left)
                && isBalanced(root.right);
    }

    private int getHeight(TreeNode node) {
        if (node == null) {
            return 0;
        }

        // 递归计算左右子树的高度,取最大值加上当前节点的高度(1)
        return 1 + Math.max(getHeight(node.left), getHeight(node.right));
    }

    public static void main(String[] args) {
        BinaryTreeBalance solution = new BinaryTreeBalance();

        // 在这里构建你的二叉树
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.left.left = new TreeNode(4);
        root.left.right = new TreeNode(5);

        // 调用isBalanced方法判断是否为平衡二叉树
        boolean result = solution.isBalanced(root);

        // 输出结果
        System.out.println("Is the binary tree balanced? " + result);
    }
}