110. Balanced Binary Tree LeetCode Solution

In this guide, you will get 110. Balanced Binary Tree LeetCode Solution with the best time and space complexity. The solution to Balanced Binary Tree problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Balanced Binary Tree solution in C++
  4. Balanced Binary Tree solution in Java
  5. Balanced Binary Tree solution in Python
  6. Additional Resources
110. Balanced Binary Tree LeetCode Solution image

Problem Statement of Balanced Binary Tree

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].
-104 <= Node.val <= 104

Complexity Analysis

  • Time Complexity: O(n\log n)
  • Space Complexity: O(h)

110. Balanced Binary Tree LeetCode Solution in C++

class Solution {
 public:
  bool isBalanced(TreeNode* root) {
    if (root == nullptr)
      return true;
    return abs(maxDepth(root->left) - maxDepth(root->right)) <= 1 &&
           isBalanced(root->left) && isBalanced(root->right);
  }

 private:
  int maxDepth(TreeNode* root) {
    if (root == nullptr)
      return 0;
    return 1 + max(maxDepth(root->left), maxDepth(root->right));
  }
};
/* code provided by PROGIEZ */

110. Balanced Binary Tree LeetCode Solution in Java

class Solution {
  public boolean isBalanced(TreeNode root) {
    if (root == null)
      return true;
    return Math.abs(maxDepth(root.left) - maxDepth(root.right)) <= 1 && //
        isBalanced(root.left) &&                                        //
        isBalanced(root.right);
  }

  private int maxDepth(TreeNode root) {
    if (root == null)
      return 0;
    return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
  }
}
// code provided by PROGIEZ

110. Balanced Binary Tree LeetCode Solution in Python

class Solution:
  def isBalanced(self, root: TreeNode | None) -> bool:
    if not root:
      return True

    def maxDepth(root: TreeNode | None) -> int:
      if not root:
        return 0
      return 1 + max(maxDepth(root.left), maxDepth(root.right))

    return (abs(maxDepth(root.left) - maxDepth(root.right)) <= 1 and
            self.isBalanced(root.left) and
            self.isBalanced(root.right))
# code by PROGIEZ

Additional Resources

See also  926. Flip String to Monotone Increasing LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.