Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Check if Binary Tree is Balanced

Medium Acceptance 77.00% Points 30.00

Given the root of a binary tree, return true if the tree is height-balanced, otherwise return false.

A binary tree is considered height-balanced if for every node in the tree, the height difference between its left and right subtrees is not more than 1.

Examples
Example 1

Example 1

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

Output: true

Explanation: For every node, the height difference between the left and right subtrees is at most 1. Therefore, the tree is balanced.

Example 2

Example 2

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

Output: false

Explanation: The left subtree is deeper than the right subtree by more than 1 at some nodes. Hence, the tree is not height-balanced.

Example 3

Example 3

Input: root = []

Output: true

Explanation: An empty tree is considered balanced because there are no nodes that violate the height condition.

Hints
Hint 1
N/A
Constraints
  • 0 = number of nodes = 105
  • -104 = Node.val = 104
Companies
Microsoft
Topics
Recursion
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions