|
| 1 | +# [Balanced Binary Tree](https://leetcode.com/problems/balanced-binary-tree/description/) |
| 2 | + |
| 3 | +## Intuition |
| 4 | + |
| 5 | +A binary tree is considered height-balanced if the depth of the left and right subtrees of every node differ by no more |
| 6 | +than one. To check if a tree is balanced, we can use a depth-first search (DFS) to compute the height of each subtree |
| 7 | +and simultaneously check for balance at each node. |
| 8 | + |
| 9 | +## Approach |
| 10 | + |
| 11 | +1. **DFS for Height and Balance Check:** |
| 12 | + - Use a helper method `dfsHeight to recursively calculate the height of each subtree. |
| 13 | + - For each node, calculate the heights of its left and right subtrees. |
| 14 | + - If the difference in height between the left and right subtrees is greater than 1, set a result flag to false, |
| 15 | + indicating the tree is not balanced. |
| 16 | + - Return the height of the current node as `1 + max(left, right)` to propagate the height up the recursion stack. |
| 17 | +2. **Global Balance Tracking:** |
| 18 | + - Use a boolean array result initialized to true. If any node is found to be unbalanced, the result flag is set to |
| 19 | + false. |
| 20 | + - Start the recursive check from the root node. |
| 21 | +3. **Return the Result:** After the recursion completes, result[0] will indicate whether the tree is balanced. |
| 22 | + |
| 23 | +## Complexity |
| 24 | + |
| 25 | +- **Time Complexity: `O(n`**, where `n` is the number of nodes in the tree. Each node is visited once to calculate its |
| 26 | + height and check for balance. |
| 27 | +- **Space Complexity: `O(h)`**, where `h` is is the height of the tree. This represents the space used by the recursive |
| 28 | + call stack. In the worst case (skewed tree), `h = n`, and in the best case (balanced tree), `h=log(n)`. |
| 29 | + |
| 30 | +## Summary |
| 31 | + |
| 32 | +This solution determines if a binary tree is balanced by recursively calculating the height of each subtree while |
| 33 | +checking the balance condition at each node. By tracking the balance in a boolean array, we ensure efficient checking |
| 34 | +with a single traversal. The approach meets the requirements with `O(n) time complexity. |
0 commit comments