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;
            
    }
};




Related Posts

Vertical Order Traversal Of A Binary Tree Problem

LeetCode 987. Given the root of a binary tree, calculate...

Univalued Binary Tree Problem

LeetCode 965. A binary tree is uni-valued if every node...

Sum Of Distances In Tree Problem

LeetCode 834. There is an undirected connected tree with n...

Smallest Subtree With All The Deepest Nodes Problem

LeetCode 865. Given the root of a binary tree, the...

Smallest String Starting From Leaf Problem

LeetCode 988. You are given the root of a binary...

Similar String Groups Problem

LeetCode 839. Two strings Xand Yare similar if we can...