Skip to content

Latest commit

 

History

History
40 lines (28 loc) · 1.17 KB

풀이_LC111.md

File metadata and controls

40 lines (28 loc) · 1.17 KB

🐿 111. Minimum Depth of Binary Tree

  • Date : 2021.06.27(일)
  • Time : 20분

Problem

  • Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
  • Note: A leaf is a node with no children.

Constraints

  • The number of nodes in the tree is in the range [0, 10^5]
  • -1000 <= Node.val <= 1000

Example

  • Input: root = [3,9,20,null,null,15,7]
  • Output: 2

풀이

    def minDepth(self, root: TreeNode) -> int:
        if root is None:
            return 0

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

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

        leftValue = self.minDepth(root.left)
        rightValue = self.minDepth(root.right)
        
        return min(leftValue,rightValue) + 1

: 이진 트리이기 때문에 왼쪽 오른쪽을 검사한다. 왼쪽 깊이와 오른쪽 깊이를 검사해서 최단 경로를 구하는 것이기 때문에 min을 이용해 값을 더한다. +1을 해준 이유는 root만 존재해도 1의 깊이가 성립하기 때문이다.