Check for balanced binary tree

Binary Trees Medium Problems Medium

Given a binary tree root, find if it is height-balanced or not.


A tree is height-balanced if the difference between the heights of left and right subtrees is not more than one for all nodes of the tree. 

Examples:

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

Output : Yes

Explanation :

Input : [1, 2, null, null, 3]

Output : No

Explanation :

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

Constraints

  • 1 <= Number of Nodes <= 105
  • 1 <= Node.val <= 105

Hints

  • We return the height of a subtree only if it is balanced. If at any point the height difference exceeds 1, we return an invalid flag (e.g., -1), allowing us to terminate early.
  • An iterative solution using level-order traversal (BFS) is possible, but it requires extra storage for tracking subtree heights, making it less efficient than the recursive approach.

Company Tags

Lyft Epic Games Roblox Freshworks Cerner Zynga DoorDash Flipkart Riot Games eBay Optum Morgan Stanley Electronic Arts IBM Dropbox Airbnb Siemens Healthineers Square HCL Technologies PayPal Twilio Zoho Teladoc Health Stripe Docker Google Microsoft Amazon Meta Apple Netflix Adobe