- Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathminimum_depth_of_binary_tree.py
35 lines (27 loc) · 1.14 KB
/
minimum_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
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
defmin_depth(root, current_depth):
ifnotroot:
return0
####################################################
# Similar to the [Recursion] approach to find the maximum depth,
# but make sure you consider these cases:
# Node that has one empty sub-tree while the other one is non-empty.
# Return the minimum depth of that non-empty sub-tree.
ifnotroot.left:
returnmin_depth(root.right, current_depth) +1;
ifnotroot.right:
returnmin_depth(root.left, current_depth) +1;
####################################################
# recursive (left and right)
left_depth=min_depth(root.left, current_depth)
right_depth=min_depth(root.right, current_depth)
current_depth=min( left_depth, right_depth) +1
returncurrent_depth
classSolution:
defminDepth(self, root: TreeNode) ->int:
returnmin_depth(root, 0)