算法刷题之判断是否平衡二叉树

判断一棵树是否是平衡二叉树,不考虑排序性,只考虑平衡性,也就是二叉树的所有左子树和右子树的深度差不超过1。

package tree;

public class BalanceTree {

   
    public static boolean IsBalanced_Solution(TreeNode root) {
        int left = getTreeDeepth(root.left);
        int right = getTreeDeepth(root.right);

        int minus = Math.abs(left-right);
        return minus<=1 && IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right);
    }

    private static int getTreeDeepth(TreeNode left) {
        if(left==null){
            return 0;
        }
        return Math.max(getTreeDeepth(left.left),getTreeDeepth(left.right))+1;
    }
}

 

你可能感兴趣的:(算法刷题,二叉树,算法)