February 21, 2025 |14.0K Views

Balanced Binary Tree or Not

Explore Courseexplore course icon
Description
Discussion

In this video, we will explore two approaches to determine whether a binary tree is height-balanced, meaning the difference in heights of the left and right subtrees is at most 1 for every node in the tree. The first approach uses top-down recursion, where we calculate the height of the left and right subtrees for each node separately. If at any point the difference in heights exceeds 1, we return false. This approach has a time complexity of O(n^2) and a space complexity of O(h), where n is the number of nodes and h is the height of the tree due to recursive function calls.

The second approach optimizes the first method by using bottom-up recursion. Instead of calculating the height of the subtrees in a separate function, we calculate the height during the same recursion and check if the tree is balanced at each node. If the tree is balanced at that node, we return the height; otherwise, we return -1 to indicate that the tree is unbalanced. This approach reduces the time complexity to O(n) and still uses O(h) space, making it more efficient. Watch the video for a detailed explanation of both approaches and how they efficiently check if a binary tree is balanced.

For more details, please go through - Balanced Binary Tree or Not