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