본문 바로가기
🖥️ 문제 풀이/리트코드(Leetcode)

[LeetCode 해석 및 풀이] 104. Maximum Depth of Binary Tree(이진 트리의 최대 깊이)

by 뒬탕 2024. 7. 4.
반응형

LeetCode 문제 해석 및 풀이 방법

 

문제 104. Maximum Depth of Binary Tree(이진 트리의 최대 깊이)

바로가기

 

문제 설명

영문

Given the root of a binary tree, return its maximum depth.

A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

 

한글

이진 트리의 root가 주어지면, 최대 깊이를 반환하십시오.

 

이진 트리의 최대 깊이는 root 노트로부터 가장 멀리 있는 노드까지의 경로에 있는 노드의 갯수입니다.

 

제한조건

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

 

입출력 예

입력 출력
root = [3,9,20,null,null,15,7] 3
root = [1,null,2] 2

 

 

해답 및 해설

파이썬 (Python)

class Solution:
    def maxDepth(self, root: Optional[TreeNode]) -> int:
        def treeDepth(head):
            if not head:
                return 0
            
            left_depth = treeDepth(head.left)
            right_depth = treeDepth(head.right)

            return max(left_depth, right_depth) + 1
        
        return treeDepth(root)

 

역시 재귀로 하위 트리의 최대 깊이를 구한 후 가장 긴 쪽에 1을 더하는 방식을 이용하였다.

반응형

댓글