Tutorialspoint
Problem
Solution
Submissions

Binary Tree is Balanced

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 10

Write a C++ program to implement the function bool isBalanced(TreeNode* root) which checks if a binary tree is height-balanced. A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one.

Example 1
  • Input: root = [3,9,20,null,null,15,7]
    • Tree structure:

      Binary Tree with Root Node 3

  • Output: true
  • Explanation:
    • The left subtree has depth 1, and the right subtree has depth 2.
    • The difference is 1, which is not greater than 1, so the tree is balanced.
Example 2
  • Input: root = [1,2,2,3,3,null,null,4,4]
    • Tree structure:  

      Binary Tree with Root Node 1
  • Output: false
  • Explanation:
    • The left subtree of the node with value 2 has depth 3, while its right subtree has depth 1.
    • The difference is 2, which is greater than 1, so the tree is not balanced.
Constraints
  • The number of nodes in the tree is in the range [0, 5000]
  • -10⁴ ≤ Node.val ≤ 10⁴
  • Time Complexity: O(n)
  • Space Complexity: O(h), where h is the height of the tree
RecursionBinary TreeHCL TechnologiesArctwist
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use a recursive approach to check the height of each subtree
  • Calculate the height of the left and right subtrees for each node
  • If the difference in heights is greater than 1, the tree is not balanced
  • Use a bottom-up approach to avoid redundant calculations
  • Return -1 to indicate an unbalanced subtree

Steps to solve by this approach:

 Step 1: Define a helper function to check the height of each subtree and detect imbalance
 Step 2: For each node, recursively calculate the height of left and right subtrees
 Step 3: If at any point an unbalanced subtree is detected, immediately return -1 to propagate the result up
 Step 4: After calculating heights of both subtrees, check if their difference exceeds 1
 Step 5: If the difference is greater than 1, return -1 to indicate an unbalanced tree
 Step 6: If the subtree is balanced, return its actual height (max height of children + 1)
 Step 7: In the main function, check if the helper function returns -1 (unbalanced) or a valid height (balanced)

Submitted Code :