GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — algorithms/tree/is_balanced.py at master · RajaRamu/algorithms Expand file tree/ Copy pathis_balanced.pyMore file actions 33 lines (28 loc) · 722 Bytes / Copy pathis_balanced.pyFile metadata and controls33 lines (28 loc) · 722 Bytes 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 def is_balanced(root): """ O(N) solution """ return -1 != get_depth(root) def get_depth(root): """ return 0 if unbalanced else depth + 1 """ if not root: return 0 left = get_depth(root.left) right = get_depth(root.right) if abs(left-right) > 1: return -1 return 1 + max(left, right) ################################ def is_balanced(root): """ O(N^2) solution """ left = max_height(root.left) right = max_height(root.right) return abs(left-right) <= 1 and is_balanced(root.left) and is_balanced(root.right) def max_height(root): if not root: return 0 return max(max_height(root.left), max_height(root.right)) + 1 |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |