clueless coding // TODO: be smarter

LeetCode 110. Balanced Binary Tree: Java Solution



Problem Statement


Given a binary tree, determine if it is height-balanced.

A “height-balanced” binary tree is defined as a binary tree in which the depth (height) of the two subtrees of every node are never different by more than one.

Function Signature (Java):
  boolean isBalanced(TreeNode root)

Inputs:
    o
   / \
  o   o

Outputs:
  true

Inputs:
    o
     \
      o
       \
        o

Outputs:
  false



TL;DR Code Solution



int helper(TreeNode root) {
    if (root == null) {
        return 0;
    }

    int right = helper(root.right);
    if (right == Integer.MIN_VALUE) return Integer.MIN_VALUE;
    int left = helper(root.left);
    if (left == Integer.MIN_VALUE) return Integer.MIN_VALUE;

    if (Math.abs(right - left) > 1) return Integer.MIN_VALUE;

    return Math.max(right, left) + 1;
}

public boolean isBalanced(TreeNode root) {
   return helper(root) != Integer.MIN_VALUE;
}