Welcome! Today we'll learn how to check if a binary tree is balanced. A balanced binary tree is one where for every node, the height difference between its left and right subtrees is at most 1. This property ensures efficient operations with O(log n) time complexity.
Now let's see an unbalanced tree. In this example, the left subtree has height 3 while the right subtree has height 1. The difference is 2, which exceeds our threshold of 1. This makes the tree unbalanced and can lead to poor performance in search operations.
Our algorithm uses a single recursive function that efficiently checks balance while calculating height. The key insight is to return negative one if any subtree is unbalanced, allowing us to detect imbalance early and propagate it up the tree. This gives us O(n) time complexity instead of the naive O(n squared) approach.
Here's the complete implementation. The helper function returns zero for null nodes, recursively calculates heights for left and right subtrees, and returns negative one if any imbalance is detected. The main function simply checks if the result is not negative one. This elegant solution runs in O(n) time and O(h) space where h is the tree height.
Welcome to the balanced binary tree checking algorithm! A balanced binary tree is a special type of binary tree where the height difference between the left and right subtrees of any node is at most one. This property ensures that operations like search, insert, and delete remain efficient with O(log n) time complexity.
Our algorithm uses a clever approach: instead of checking balance and calculating height separately, we do both in a single recursive traversal. The key insight is to return negative one when we detect an unbalanced subtree, allowing us to propagate the imbalance detection up the tree immediately. This gives us optimal O(n) time complexity.
Here's the implementation. We use a nested helper function called checkHeight that returns negative one if the subtree is unbalanced, otherwise it returns the actual height. The main function simply checks if the result is not negative one. Notice how we check for imbalance immediately after each recursive call, allowing for early termination.
Let's trace through an unbalanced tree example. We start from the leaves and work our way up. Node 5 returns height 0, node 4 returns height 1, node 2 returns height 2. Node 3 returns height 0. Finally, at the root node 1, we check the height difference: 2 minus 0 equals 2, which is greater than 1, so we return negative 1, indicating the tree is unbalanced.
To summarize, our balanced binary tree checking algorithm achieves optimal O(n) time complexity by combining height calculation with balance checking in a single traversal. This is significantly better than the naive approach which would be O(n squared). The algorithm is practical for real-world applications and forms the foundation for self-balancing tree data structures like AVL trees.