-
Notifications
You must be signed in to change notification settings - Fork 134
/
Minimum_height.py
40 lines (30 loc) · 885 Bytes
/
Minimum_height.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
# Find minimum depth of a binary tree
from collections import deque
# A Binary Tree node
class Node:
# Constructor to initialise node
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def get_min_depth(root):
if root is None:
return 0
queue = deque()
queue.append((root, 1))
while queue:
node, height = queue.popleft()
if node.left is None and node.right is None:
return height
else:
if node.left is not None:
queue.append((node.left, height + 1))
if node.right is not None:
queue.append((node.right, height + 1))
if __name__ == '__main__':
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
print(get_min_depth(root))