|
| 1 | +# 110. Balanced Binary Tree |
| 2 | + |
| 3 | +## Recursive solution |
| 4 | + |
| 5 | +- Runtime: O(N) |
| 6 | +- Space: O(H) |
| 7 | +- N = Number of elements in list |
| 8 | +- H = Height of tree |
| 9 | + |
| 10 | +Since the definition of a balance tree is that for each node the difference between each children's height is never greater than 1. We can perform a post order traversal and then compare the heights given by both children. If we encounter an imbalance, we ignore anymore traversals and head back up to the root node using an arbitrary value like -1 to symbolize an imbalance. |
| 11 | + |
| 12 | +Worst case is if the tree is balanced and we have to visit every node. |
| 13 | +However, no matter what, we will end up using at most O(H) space to traverse the tree. |
| 14 | + |
| 15 | +``` |
| 16 | +class Solution: |
| 17 | + def isBalanced(self, root: TreeNode) -> bool: |
| 18 | + |
| 19 | + def balance_helper(root): |
| 20 | + if root is None: |
| 21 | + return 0 |
| 22 | + left = balance_helper(root.left) |
| 23 | + right = balance_helper(root.right) |
| 24 | + if left == -1 or right == -1: |
| 25 | + return -1 |
| 26 | + return max(left+1, right+1) if abs(left-right) <= 1 else -1 |
| 27 | + |
| 28 | + return True if balance_helper(root) != -1 else False |
| 29 | +``` |
0 commit comments