Java日记2018-07-24

2018-07-24  本文已影响0人  hayes0420

Balanced Binary Tree
高度平衡二叉树是每一个节点的两个字数的深度差不能超过1,

public static boolean isBalance(TreeNode root){
        if(root == null) return false;
        if(depth(root)==-1) {
            return false;
        } else{
            return true;
        }
    }
    public static int depth(TreeNode root){
        if(root==null) return 0;
        int left = depth(root.left);
        int right = depth(root.right);
        if(left==-1) return -1;
        if(right ==-1) return -1;
        if(Math.abs(right-left)>1){
            return -1;
        } else{
            return Math.max(right, left)+1;
        }
        
    }
上一篇 下一篇

猜你喜欢

热点阅读