用java刷剑指offer(平衡二叉树)
题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
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;
}
}

更多精彩