0110 - Balance Binary Tree

0110 - Balance Binary Tree

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.

Examples

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

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

Input: root = [] Output: true

Constraints

The number of nodes in the tree is in the range [0, 5000]. -104 <= Node.val <= 104

Java Solution

Bottom Up Recursion

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public boolean isBalanced(TreeNode root) {
        return height(root) != -1;
    }
    
    public int height(TreeNode root) {
        if(root == null) return 0;
        
        int left = height(root.left);
        int right = height(root.right);
        
        if (Math.abs(left - right) > 1 || left == -1 || right == -1) return -1;
        return Math.max(left, right) + 1;
    }
}

Last updated