Published:
Updated:

  • Reference
  • ์‹œ๊ฐ„๋ณต์žก๋„: $O(N)$
  • Runtime 54ms
  • Beats 27.2%
  • ์ด๊ฑฐ ์ ˆ๋Œ€ easy ์•„๋‹ˆ๋‹ค..


Solution

# Definition for a binary tree node.
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:
    # root๋ฅผ ์ง€๋‚  ์ˆ˜๋„ ์žˆ๊ณ , ์•ˆ ์ง€๋‚  ์ˆ˜๋„ ์žˆ์Œ
    # ๊ฑฐ๊พธ๋กœ ์˜ฌ๋ผ๊ฐ€์•ผ ๋จ
    def __init__(self):
        self.branch_count = None

    def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:
        # self๋ฅผ ๋ถ™์ด๋ฉด ์ด ํด๋ž˜์Šค์˜ ์ธ์Šคํ„ด์Šค ๋ณ€์ˆ˜๋ฅผ ์ƒ์„ฑํ•ด์ค€๋‹ค๋Š” ๋œป์ž„
        # ๊ทธ๋ž˜์„œ self๋กœ ํด๋ž˜์Šค ๋‚ด์— ์žˆ๋Š” ๋ชจ๋“  ์ธ์Šคํ„ด์Šค ๋ฉ”์„œ๋“œ์—์„œ ์‚ฌ์šฉ ๊ฐ€๋Šฅ (์—ฌ๊ธฐ์„  dfs())
        # ๊ฒฐ๋ก : self == instance, ์ž๋ฐ” ์ธ์Šคํ„ด์Šค๋ž‘ ๋˜‘๊ฐ™์Œ (private ์ฒ˜๋ฆฌ ์•ˆ ๋œ ์ธ์Šคํ„ด์Šค ๋ณ€์ˆ˜)
        self.branch_count = 0

        # run()
        self.dfs(root)

        return self.branch_count

    def dfs(self, node):
        # node๊ฐ€ null์ด๋ฉด 0 ๋ฆฌํ„ด
        if node is None:
            return 0

        # ๋งˆ์ง€๋ง‰ ๋…ธ๋“œ๋ถ€ํ„ฐ ์ฐพ๊ณ  (์žฌ๊ท€ ์ด์šฉ)
        left = self.dfs(node.left)
        right = self.dfs(node.right)

        # ์ด์ œ ๊ฑฐ๊พธ๋กœ ์˜ฌ๋ผ๊ฐ€์•ผ์ง€
        # ๋…ธ๋“œ๋ฅผ ํ†ต๊ณผํ•˜๋Š” ๊ฐ€์žฅ ๊ธด ๋‚˜๋ญ‡๊ฐ€์ง€ ๊ณ„์‚ฐ (๊ฐ๊ฐ์˜ left์™€ right์˜ ๊ฒฝ๋กœ)
        # left์™€ right์˜ ์ž์‹ ๋…ธ๋“œ ๊ฑฐ๋ฆฌ์˜ ํ•ฉ์˜ ์ตœ๋Œ“๊ฐ’
        self.branch_count = max(self.branch_count, left + right)
        # ์žฌ๊ท€ํ•จ์ˆ˜ ์ง€๋‚˜๊ฐˆ ๋•Œ๋งˆ๋‹ค 1์”ฉ ์ฆ๊ฐ€ํ•ด์•ผ ๋˜๋‹ˆ
        # ์ž์‹ ๋…ธ๋“œ ์ค‘ ํฐ ๊ฐ’
        return max(left, right) + 1

Leave a comment