Minimum Depth of Binary Tree LeetCode solution in Python

1
class Solution(object):
2
def minDepth(self, root):
3
# Base case...
4
# If the subtree is empty i.e. root is NULL, return depth as 0...
5
if root is None:
6
return 0
7
# Initialize the depth of two subtrees...
8
leftDepth = self.minDepth(root.left)
9
rightDepth = self.minDepth(root.right)
10
# If the both subtrees are empty...
11
if root.left is None and root.right is None:
12
return 1
13
# If the left subtree is empty, return the depth of right subtree after adding 1 to it...
14
if root.left is None:
15
return 1 + rightDepth
16
# If the right subtree is empty, return the depth of left subtree after adding 1 to it...
17
if root.right is None:
18
return 1 + leftDepth
19
# When the two child function return its depth...
20
# Pick the minimum out of these two subtrees and return this value after adding 1 to it...
21
return min(leftDepth, rightDepth) + 1
22
# Adding 1 is the current node which is the parent of the two subtrees...

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0