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

题目描述

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

牛客网链接

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;
    }
}
posted @ 2019-11-15 11:29  1Shuan  阅读(259)  评论(0编辑  收藏  举报