|
| 1 | +# Problem: Balanced Binary Tree |
| 2 | +# Link: https://leetcode.com/problems/balanced-binary-tree/description/ |
| 3 | +# Tags: Tree, DFS, Recursion, Divide and Conquer |
| 4 | +# Approach: Use a post-order DFS that computes subtree heights and detects imbalance early. |
| 5 | +# For each node, obtain left and right heights; if either subtree is already |
| 6 | +# unbalanced or their height difference exceeds 1, propagate an unbalanced signal. |
| 7 | +# Otherwise return 1 + max(left_height, right_height). This short-circuits on the |
| 8 | +# first violation and visits each node once. |
| 9 | +# Time Complexity: O(n) |
| 10 | +# Space Complexity: O(h) where h is the tree height |
| 11 | + |
| 12 | + |
| 13 | +class Solution: |
| 14 | + def isBalanced(self, root): |
| 15 | + def dfs(node): |
| 16 | + if not node: |
| 17 | + return True, 0 |
| 18 | + lb, lh = dfs(node.left) |
| 19 | + if not lb: |
| 20 | + return False, 0 |
| 21 | + rb, rh = dfs(node.right) |
| 22 | + if not rb: |
| 23 | + return False, 0 |
| 24 | + ok = abs(lh - rh) <= 1 |
| 25 | + return ok, 1 + (lh if lh > rh else rh) |
| 26 | + |
| 27 | + ok, _ = dfs(root) |
| 28 | + return ok |
0 commit comments