-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathMin Depth of Binary Tree.py
73 lines (50 loc) · 1.56 KB
/
Min Depth of Binary Tree.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
"""
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
NOTE : The path has to end on a leaf node.
Example :
1
/
2
min depth = 2.
"""
from Python.Level6.TreeDataStructure import Node
class Solution:
def min_depth(self, root):
if root is None:
return 0
if root.left is None and root.right is None:
return 1
if root.left is None:
return self.min_depth(root.right) + 1
if root.right is None:
return self.min_depth(root.left) + 1
return min(self.min_depth(root.left), self.min_depth(root.right)) + 1
def min_depth_02(self, root):
if root is None:
return 0
queue = []
queue.append((root, 1))
while queue:
node, depth = queue.pop()
if node.left is None and node.right is None:
return depth
if node.left is not None:
queue.append((node.left, depth + 1))
if node.right is not None:
queue.append((node.right, depth + 1))
"""Testing program"""
s = Solution()
root = Node(5)
root.left = Node(4)
root.right = Node(8)
root.left.left = Node(11)
root.right.left = Node(13)
root.right.right = Node(4)
root.left.left.left = Node(7)
root.left.left.right = Node(2)
root.right.right.right = Node(1)
root.right.right.left = Node(5)
root.right.right.left.right = Node(90)
print(s.min_depth(root))
print(s.min_depth_02(root))