题目描述

输入一棵二叉树,判断该二叉树是否是平衡二叉树。

牛客网链接

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

java代码

import java.lang.Math;

public class Solution {
    public boolean IsBalanced_Solution(TreeNode root) {
        if (root == null) return true;
        return getDeepth(root) != -1;
        
    }
    private int getDeepth(TreeNode root) {
        if (root == null) return 0;
        int left = getDeepth(root.left);
        if (left == -1) return -1;
        int right = getDeepth(root.right);
        if (right == -1) return -1;
        if (Math.abs(left-right) > 1) return -1;
        return Math.max(left, right) + 1;
    }
}
扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄