Balanced Binary Tree

73 阅读1分钟

Description

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

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

Constraints:

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

Train of thought

  • Firstly, finding base cases determine whether the root is null. Secondly, determine how to recursive?

  • Calculate the height of the left subtree and right subtree. Determine whether the height difference between the left and right subtrees is > 1

Solution

public static boolean isBalanced(TreeNode root) {
    if (root == null) {
        return true;
    }
    return getBalanced(root) != -1;
}

public static int getBalanced(TreeNode root) {
    if (root == null) {
        return 0;
    }
    // Height of left subtree
    int lHeight = getBalanced(root.left);
    // Height of right subtree
    int rHeight = getBalanced(root.right);
    // 
    if (lHeight == -1 || rHeight == -1) {
        return -1;
    }
    // Determine whether the height difference between the left and right subtrees is > 1
    if (Math.abs(rHeight - lHeight) > 1) {
        return -1;
    }
    // Returns the height of the highest subtree
    return Math.max(lHeight, rHeight) + 1;
}