Simple JAVA Solution


  • 0

    Define a getDepth method, which will return the height of the tree, if it is balanced, otherwise, return -1.
    ...

    public boolean isBalanced(TreeNode root) {
        return getDepth(root) != -1;
    }
    
    private int getDepth(TreeNode root) {
        if (root != null) {
            int left = getDepth(root.left);
            int right = getDepth(root.right);
            
            return (left == -1 || right == -1 || Math.abs(left-right) > 1) ? -1 : Math.max(left, right) + 1;
        }
        
        return 0;
    }
    

    ...


Log in to reply
 

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