java 判断一个二叉树是不是平衡二叉树

题目:

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. 

算法如下:

/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */
public class Solution {
    public boolean isBalanced(TreeNode root) {
        if(root==null) return true;
        if(root.left==null&&root.right==null)
            return true;
        if(root.left==null&&root.right!=null){
            root = root.right;
            if(root.left==null&&root.right==null)
                return true;
            else
                return false;
        }

        if(root.right==null&&root.left!=null){
            root = root.left;
            if(root.left==null&&root.right==null)
                return true;
            else
                return false;
        }
        if(root.right!=null&&root.left!=null){
            boolean flag1 = isBalanced(root.right);
            boolean flag2 = isBalanced(root.left);
            if(!(flag1&&flag2))
                return false;
            else{
                int x = Math.abs(maxDepth(root.left)-maxDepth(root.right));
                if(x>1){
                    return false;
                }else{
                    return true;
                }
            }

        }
        return true;
    }

    public int maxDepth(TreeNode root){
        if(root==null){
            return 0;
        }
        if(root.left==null&&root.right==null){
            return 1;
        }
        if(root.left==null){
            return maxDepth(root.right)+1;
        }
        if(root.right==null){
            return maxDepth(root.left)+1;
        }
        if(root.left!=null&&root.right!=null){
            return max(maxDepth(root.left),maxDepth(root.right))+1;
        }

        return 0;
    }

    public int max(int a,int b){
        return a>b?a:b;
    }
}
    原文作者:平衡二叉树
    原文地址: https://blog.csdn.net/diu_brother/article/details/51263123
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞