Solution: Balanced Binary Tree
Let's solve the Balanced Binary Tree problem using the Tree Depth-first Search pattern.
We'll cover the following
Statement#
Given a binary tree with nodes, return TRUE if it is height-balanced. Otherwise, return FALSE.
Note: The height of an empty tree is .
Constraints:
-
Node.data
Solution#
A balanced binary tree is one where the heights of the left and right subtrees of each node differ by at most
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
If the node is NULL, return
because it indicates an empty tree and the height of an empty tree is . Calculate the height of the left subtree recursively. If the left subtree is imbalanced, we return
. In the similar manner, calculate the height of the right subtree. If the right subtree is imbalanced, we return
. 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
, we return indicating that the current subtree is not balanced. If the current subtree is balanced, we return the height of this subtree by adding
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
Let’s look at the following illustration to get a better understanding of the solution:
1 of 11
2 of 11
3 of 11
4 of 11
5 of 11
6 of 11
7 of 11
8 of 11
9 of 11
10 of 11
11 of 11
Let’s implement the algorithm as discussed above:
Balanced Binary Tree
Invert Binary Tree