目 录CONTENT

文章目录

平衡二叉树

小磊
2023-04-25 / 0 评论 / 0 点赞 / 522 阅读 / 168 字 / 正在检测是否收录...

LeetCode 110 平衡二叉树

给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。

public class BalancedBinaryTree {

    public boolean isBalanced(TreeNode root) {
        return method(root).isBalance;
    }

    public class ResultDate {
        int high;
        boolean isBalance;

        public ResultDate() {
        }

        public ResultDate(int high, boolean isBalance) {
            this.high = high;
            this.isBalance = isBalance;
        }
    }

    public ResultDate method(TreeNode root) {
        if (null == root) {
            return new ResultDate(0, true);
        }
        ResultDate leftResultDate = method(root.left);
        ResultDate rightResultDate = method(root.right);

        int high = Math.max(leftResultDate.high, rightResultDate.high) + 1;
        boolean isBalance = false;
        if ((Math.abs(leftResultDate.high - rightResultDate.high) < 2) && leftResultDate.isBalance && rightResultDate.isBalance) {
            isBalance = true;
        }
        return new ResultDate(high, isBalance);
    }
}
0

评论区