Check for balanced binary tree

Binary Trees Medium Problems Medium
  • The concept of checking if a binary tree is height-balanced is crucial in the development of databases and file systems, where balanced-tree data structures like AVL trees and Red-Black trees are used
  • An AVL tree, for instance, is a self-balancing binary search tree, and the heights of the two child subtrees of any node differ by at most one
  • This ensures that lookups, insertions, and deletions are all fast, optimizing overall system performance

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