-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy path4.4-Check_Balanced.py
78 lines (55 loc) · 1.85 KB
/
4.4-Check_Balanced.py
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# CTCI 4.4
# Check Balanced
import unittest
import math
import sys
class Node():
def __init__(self, left=None, right=None):
self.left, self.right = left, right
# My Solution
# Uses 99999999 as an error code when not balanced
# Should use max int?
def is_balanced(root):
return checkHeight(root) != 99999999
def checkHeight(root):
if root is None:
return -1
leftHeight = checkHeight(root.left)
if leftHeight == 99999999:
return 99999999
rightHeight = checkHeight(root.right)
if rightHeight == 99999999:
return 99999999
if abs(leftHeight - rightHeight) > 1:
return 99999999
return max(leftHeight, rightHeight) +1
# First brute force O(nlogn)
def check_balanced(root):
if not root:
return True
left = get_height(root.left, 0)
right = get_height(root.right, 0)
if left == right or left == right+1 or left == right-1:
return is_balanced(root.left) and is_balanced(root.right)
return False
# Brute force to get height
def get_height(root, height):
if not root:
return height
return max(get_height(root.left, height+1), get_height(root.right, height+1))
#-------------------------------------------------------------------------------
# CTCI Solution
#-------------------------------------------------------------------------------
#Testing
class Test(unittest.TestCase):
def test_is_balanced(self):
self.assertEqual(is_balanced(Node(Node(),Node())), True)
self.assertEqual(is_balanced(Node(Node(),Node(Node()))), True)
self.assertEqual(is_balanced(Node(Node(),Node(Node(Node())))),
False)
self.assertEqual(is_balanced(Node(Node(Node()),Node(Node(Node())))),
False)
self.assertEqual(is_balanced(Node(Node(Node()),
Node(Node(Node()),Node()))), True)
if __name__ == "__main__":
unittest.main()