Tutorialspoint
Problem
Solution
Submissions

Balanced Binary Tree

Certification: Basic Level Accuracy: 0% Submissions: 0 Points: 5

Write a C program to determine if a binary tree is height-balanced. A height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differs by more than 1.

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




  • Output: true
  • Explanation:
    1. The depth of the subtree rooted at 9 is 1.
    2. The depth of the subtree rooted at 20 is 2.
    3. The difference between these depths is |1-2| = 1, which is not more than 1.
    4. All other nodes (15 and 7) have balanced subtrees.
    5. Therefore, the tree is height-balanced.
Example 2
  • Input: root = [1,2,2,3,3,null,null,4,4]




  • Output: false
  • Explanation:
    1. The depth of the left subtree of the root (rooted at node 2) is 3.
    2. The depth of the right subtree of the root (rooted at the other node 2) is 1.
    3. The difference between these depths is |3-1| = 2, which is more than 1.
    4. Therefore, the tree is not height-balanced.
Constraints
  • The number of nodes in the tree is in the range [0, 5000]
  • -10^4 <= Node.val <= 10^4
  • Time Complexity: O(n) where n is the number of nodes
  • Space Complexity: O(h) where h is the height of the tree 
  • You need to check balance for every node in the tree
Binary TreeeBaySwiggy
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 calculate the height of each subtree
  • For a tree to be balanced, each subtree must also be balanced
  • Consider a bottom-up approach to avoid redundant calculations
  • A post-order traversal can be efficient for this problem
  • Consider using a special return value to indicate an unbalanced subtree

Steps to solve by this approach:

 Step 1: Create a helper function that recursively calculates the height of a subtree.

 Step 2: In this helper function, use -1 as a special return value to indicate that a subtree is unbalanced.
 Step 3: For each node, first check if its left subtree is balanced by recursively calling the helper function.
 Step 4: Then check if its right subtree is balanced using the same approach.
 Step 5: If either subtree is unbalanced (returns -1), immediately return -1 to indicate the entire tree is unbalanced.
 Step 6: If both subtrees are balanced, check if their heights differ by more than 1. If so, return -1.
 Step 7: If the current node is balanced, return its height (1 + maximum height of its subtrees).

Submitted Code :