剑指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;
    }
}
    原文作者:平衡二叉树
    原文地址: https://blog.csdn.net/JingLisen/article/details/82011943
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞