Published:
Updated:


Solution

# ์ด์ง„ ํŠธ๋ฆฌ ๋ฃจํŠธ๊ฐ€ ์ฃผ์–ด์ง€๋ฉด -> ๊ทธ ์ตœ๋Œ€ ๊นŠ์ด ๋ฆฌํ„ด
# ์ด์ง„ ํŠธ๋ฆฌ์˜ ์ตœ๋Œ€ ๊นŠ์ด -> ๋ฃจํŠธ ๋…ธ๋“œ์—์„œ ๊ฐ€์žฅ ๋จผ ๋ฆฌํ”„ ๋…ธ๋“œ๊นŒ์ง€ ๊ฐ€์žฅ ๊ธด ๊ฒฝ๋กœ์˜ ๋…ธ๋“œ ์ˆ˜

from typing import Optional


class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution:
    def maxDepth(self, root: Optional[TreeNode]) -> int:
        # ์žฌ๊ท€(์•„๋ž˜์—์„œ ์œ„๋กœ) -> ์ตœ๋Œ€ ๊นŠ์ด: ์ขŒ์ธก ์ž์‹ ํŠธ๋ฆฌ์™€, ์šฐ์ธก ์ž์‹ ํŠธ๋ฆฌ ์ค‘ ํฐ ๊ฐ’
        if not root:
            return 0

        return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1

        # ์Šคํƒ(์œ„์—์„œ ์•„๋ž˜๋กœ) -> ๊ฒฝ์šฐ์— ๋”ฐ๋ผ ๋” ๋ณต์žก์“ฐ
        # if not root:
        #     return 0
        #
        # max_depth = 0
        # stack = [(root, 1)]
        # while stack:
        #     node, depth = stack.pop()
        #     max_depth = max(depth, max_depth)
        #     if node.left:
        #         stack.append((node.left, depth + 1))
        #     if node.right:
        #         stack.append((node.right, depth + 1,))
        #
        # return max_depth

Leave a comment