Minimum Depth of Binary Tree

Problem Id: 111 Difficulty: Easy Tag: Tree Tag: Depth-first Search Breadth-first Search


Intuition

This problem could be solved recursivly by DFS.

Solution


# 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 is None:
            return 0
        if root.left == root.right == None:
            return 1

        if root.right is None:
            return self.minDepth(root.left) + 1
        if root.left is None:
            return self.minDepth(root.right) + 1
        return min(self.minDepth(root.left), self.minDepth(root.right)) + 1