
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: - Output: true
- Explanation:
- Each subtree height difference ≤ 1
Example 2
- Input:
- 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)
Editorial
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. |
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.