用java刷剑指offer(平衡二叉树)

时间:2021-04-15 14:57:45

题目描述

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

牛客网链接

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;
}
}