Simple Java solution with recursion


  • -1
    C

    First of all, we need to have a function to check the height of the tree starting from a node.
    After we have this function it is very simple, we check the height of the left child node and the height of the right child node, if the differ more than 1 return false, else we recursively check it's left and right children.

       public boolean isBalanced(TreeNode root) {
        if(root == null){
            return true;
        }
        int leftHeight = height(root.left);
        int rightHeight = height(root.right);
        if(Math.abs(leftHeight - rightHeight) > 1){
            return false;
        }
        return isBalanced(root.left) && isBalanced(root.right);
    }
    public int height(TreeNode root){
        if(root == null){
            return 0;
        }
        return Math.max(height(root.left), height(root.right)) +1;
    }

Log in to reply
 

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