
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:
- Tree structure:
- 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:
- Tree structure:
- 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
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 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