Balanced Binary Tree Problem
Description
LeetCode Problem 110.
Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary tree is defined as: a binary tree in which the left and right subtrees of every node differ in height by no more than 1.
Example 1:
1
2
Input: root = [3,9,20,null,null,15,7]
Output: true
Example 2:
1
2
Input: root = [1,2,2,3,3,null,null,4,4]
Output: false
Example 3:
1
2
Input: root = []
Output: true
Constraints:
- The number of nodes in the tree is in the range [0, 5000].
- -10^4 <= Node.val <= 10^4
Sample C++ Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
bool is_balanced;
int bfs(TreeNode* node, int h) {
if (node == NULL)
return h-1;
int left_h = bfs(node->left, h+1);
int right_h = bfs(node->right, h+1);
if (abs(left_h-right_h) > 1)
is_balanced = false;
return max(left_h, right_h);
}
bool isBalanced(TreeNode* root) {
is_balanced = true;
bfs(root, 1);
return is_balanced;
}
};