A Java 2ms concise solution easy to understand


  • 2
    L
    //The point to solve it by using recursive is to use integer value as 
    //both height counter and a flag to mark unbalance. I'm feeling it's a middle level problem to solve.
    public boolean isBalanced(TreeNode root) {
        return root == null || height(root) != -1;
    }
    private int height(TreeNode root){
        if(root.left == null && root.right == null)
            return 1;
        int lH = 0, rH = 0;
        if(root.left != null) lH = height(root.left);
        if(root.right != null) rH = height(root.right);
        if(lH == -1 || rH == -1) return -1;
        if(Math.abs(lH - rH) > 1) return -1;
        return Math.max(lH, rH) + 1;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.