-
Notifications
You must be signed in to change notification settings - Fork 19
/
4.3-List_Of_Depths.py
76 lines (57 loc) · 1.79 KB
/
4.3-List_Of_Depths.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
# CTCI 4.3
# List of Depths
import unittest
import math
class TreeNode():
def __init__(self, data=None, left=None, right=None):
self.data, self.left, self.right = data, left, right
self.depth = None
class ListNode():
def __init__(self, data=None, next=None):
self.data, self.next = data, next
def __str__(self):
return str(self.data) + ',' + str(self.next)
# My Solution
def list_of_depths(tree):
# Don't need a visited data structure because not a graph
queue = []
curr = tree
result = []
level = 0
if curr:
result.append([curr])
else:
return []
while True:
if not result[level]:
break
result.append([])
for n in result[level]:
if n.left:
result[level+1].append(n.left)
if n.right:
result[level+1].append(n.right)
level += 1
return result
#-------------------------------------------------------------------------------
# CTCI Solution
#-------------------------------------------------------------------------------
#Testing
class Test(unittest.TestCase):
def test_list_of_depths(self):
node_h = TreeNode('H')
node_g = TreeNode('G')
node_f = TreeNode('F')
node_e = TreeNode('E', node_g)
node_d = TreeNode('D', node_h)
node_c = TreeNode('C', None, node_f)
node_b = TreeNode('B', node_d, node_e)
node_a = TreeNode('A', node_b, node_c)
lists = list_of_depths(node_a)
self.assertEqual((lists[0]), [node_a])
self.assertEqual((lists[1]), [node_b, node_c])
self.assertEqual((lists[2]), [node_d, node_e, node_f])
self.assertEqual((lists[3]), [node_h, node_g])
#self.assertEqual(len(lists), 4)
if __name__ == "__main__":
unittest.main()