Balanced Binary Tree

Balanced Binary Tree

Sergei Golitsyn

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

For this problem, a height-balanced binary tree is defined as:

a binary tree in which the left and right subtrees of every node differ in height by no more than 1.

Example 1:

Input: root = [3,9,20,null,null,15,7]
Output: true


Example 2:

Input: root = [1,2,2,3,3,null,null,4,4]
Output: false

Example 3:

Input: root = []
Output: true


Solution:

This is one of the base tree problems.

To understand if it is a height-balanced tree, we should know the height of the left and right subtree. And... and that is it. we can check recursively left and right sub tree and return max depth.

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

Report Page