Tutorialspoint
Problem
Solution
Submissions

Check if Tree is Balanced

Certification: Basic Level Accuracy: 75% Submissions: 4 Points: 5

Write a Java program to determine if a binary tree is balanced. A balanced binary tree is one where the height difference between the left and right subtrees of every node is not more than 1.

Example 1
  • Input:
    Tree:

    Tree Balancing with height Greater than one

  • Output: true
  • Explanation:
    • Each subtree height difference ≤ 1
Example 2
  • Input:

    Tree Balancing with height less than equal to one

  • Output: false
  • Explanation:
    • Subtree height difference > 1 in some nodes
Constraints
  • 0 ≤ number of nodes ≤ 5000
  • -10^4 ≤ Node.val ≤ 10^4
  • Time Complexity: O(n)
  • Space Complexity: O(h)
TreeWalmartSwiggy
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

  • Calculate the height of left and right subtrees for each node.
  • Check if the difference between heights is not more than 1.
  • Recursively check balance for left and right subtrees.
  • Use a depth-first approach to traverse the tree.
  • Consider an approach that avoids recalculating heights by calculating height and checking balance in a single traversal.

Steps to solve by this approach:

 Step 1: Define a helper method that checks both height and balance in a single traversal.

 Step 2: For each node, recursively check the height and balance of left and right subtrees.
 Step 3: If a subtree is unbalanced (height difference > 1), return -1 to indicate unbalanced state.
 Step 4: If a subtree is balanced, return its actual height.
 Step 5: For empty nodes (null), return height 0.
 Step 6: At each node, calculate height difference between left and right subtrees.
 Step 7: If the difference exceeds 1, the tree is unbalanced; otherwise, return the height of the current node.

Submitted Code :