-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmin_tree_depth.py
72 lines (49 loc) · 1.2 KB
/
min_tree_depth.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
class TreeNode():
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def __repr__(self):
return '<TreeNode {}>'.format(self.val)
def min_depth(node, depth=1):
if node.left is None and node.right is None:
return depth
if node.left is None:
return min_depth(node.right, depth+1)
if node.right is None:
return min_depth(node.left, depth+1)
return min(
min_depth(node.left, depth+1),
min_depth(node.right, depth+1)
)
def create_test_tree():
n1 = TreeNode(1)
n2 = TreeNode(2)
n3 = TreeNode(3)
n4 = TreeNode(4)
n5 = TreeNode(5)
n6 = TreeNode(6)
n4.left = n2
n4.right = n6
n2.left = n1
n2.right = n3
n6.left = n5
root = n4
return root
def test_min_depth():
root = create_test_tree()
assert min_depth(root) == 3
def test_min_depth_no_left_side():
n2 = TreeNode(2)
n3 = TreeNode(3)
n2.right = n3
root = n2
assert min_depth(root) == 2
def test_min_depth_leaf_node():
n1 = TreeNode(1)
n2 = TreeNode(2)
n3 = TreeNode(3)
n1.left = n2
n2.right = n3
root = n1
assert min_depth(root) == 3