剑指offer编程试题Java实现--39.平衡二叉树

个人博客:小景哥哥

39.平衡二叉树

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


public class Solution {
    public boolean IsBalanced_Solution(TreeNode root) {
        if(root == null)
            return true;
        int left = TreeDepth(root.left);
        int right = TreeDepth(root.right);
        int diff = left - right;
        if( diff > 1 || diff < -1)
            return false;
        return IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right);
    }

    public int TreeDepth(TreeNode root) {
        if(root == null)
            return 0;
        if(root != null && root.left == null && root.right == null)
            return 1;
        int leftLen = TreeDepth(root.left);
        int rightLen = TreeDepth(root.right);
        return leftLen > rightLen? leftLen + 1: rightLen + 1;
    }
}

你可能感兴趣的:(Java基础)