Minimum Depth of Binary Tree – Python 3 (Week 12 – 20)

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def minDepth(self, root: TreeNode) -> int:
        if root == None:
            return 0
        elif root.right == None and root.left == None:
            return 1
        elif root.right == None:
            depth = self.minDepth(root.left) + 1
        elif root.left == None:
            depth = self.minDepth(root.right) + 1
        else:   
            depth = min(self.minDepth(root.right), self.minDepth(root.left)) + 1
        
        return depth

Time O(d). Space O(d).

Leave a comment

Design a site like this with WordPress.com
Get started