Solution: Balanced Binary Tree

Let's solve the Balanced Binary Tree problem using the Tree Depth-first Search pattern.

Statement#

Given a binary tree with nn nodes, return TRUE if it is height-balanced. Otherwise, return FALSE.

Note: The height of an empty tree is 00.

Constraints:

  • 1n5001 \leq n \leq 500
  • 104-10^4 \leq Node.data 104\leq 10^4

Solution#

A balanced binary tree is one where the heights of the left and right subtrees of each node differ by at most 11. To check if a tree is balanced, we look at each node and calculate the heights of its left and right subtrees. If the height difference is more than 11 at any node, it’s considered imbalanced. If all nodes have a height difference of at most 11, the tree is considered balanced.

The steps of the abovementioned algorithm are given below:

Create a recursive helper function is_balanced_helper that returns the height of a subtree rooted at the given node. If the subtree is imbalanced, it returns 1-1. The steps of the recursive function are given below:

  • If the node is NULL, return 00 because it indicates an empty tree and the height of an empty tree is 00.

  • Calculate the height of the left subtree recursively. If the left subtree is imbalanced, we return 1-1.

  • In the similar manner, calculate the height of the right subtree. If the right subtree is imbalanced, we return 1-1.

  • If both left and right subtrees are balanced, we calculate the difference between the heights of the left and right subtrees. If the difference is more than 11, we return 1-1 indicating that the current subtree is not balanced.

  • If the current subtree is balanced, we return the height of this subtree by adding 11 to the maximum height of the left and right subtrees.

The is_balanced function uses the helper function is_balanced_helper to check if the tree is balanced; it returns TRUE if all nodes have valid heights and FALSE if any node returns 1-1, indicating an imbalance.

Let’s look at the following illustration to get a better understanding of the solution:

canvasAnimation-image

1 of 11

canvasAnimation-image

2 of 11

canvasAnimation-image

3 of 11

canvasAnimation-image

4 of 11

canvasAnimation-image

5 of 11

canvasAnimation-image

6 of 11

canvasAnimation-image

7 of 11

canvasAnimation-image

8 of 11

canvasAnimation-image

9 of 11

canvasAnimation-image

10 of 11

canvasAnimation-image

11 of 11

Let’s implement the algorithm as discussed above:

main.py
TreeNode.py
BinaryTree.py
Balanced Binary Tree

Time complexity#

The time complexity of the above solution is O(n)O(n), where nn is the total number of nodes in the tree.

Space complexity#

The space complexity of the above solution is O(n)O(n), because of the recursive call stack.

Balanced Binary Tree

Invert Binary Tree