Zero to Hero
article thumbnail
Published 2021. 4. 16. 10:51
104. Maximum Depth of Binary Tree Algorithm
 

Maximum Depth of Binary Tree - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

1. DFS를 이용한 내 풀이

class Solution:
    answer = 0

    def maxDepth(self, root: TreeNode) -> int:

        def dfs(cur, depth):
            self.answer = max(self.answer, depth)
            if cur.left:
                dfs(cur.left, depth + 1)
            if cur.right:
                dfs(cur.right, depth + 1)
        if not root:
            return 0
        dfs(root, 0)
        return self.answer+1

 

2. 직관적이고 섹시한 풀이

class Solution:

    def maxDepth(self, root: TreeNode) -> int:
        if not root:
            return 0
        return 1 + max(self.maxDepth(root.right), self.maxDepth(root.left))

 

'Algorithm' 카테고리의 다른 글

2174번: 로봇 시뮬레이션  (0) 2021.04.18
7. Reverse Integer  (0) 2021.04.17
13549번: 숨바꼭질 3  (0) 2021.04.15
283. Move Zeroes  (0) 2021.04.15
787. Cheapest Flights Within K Stops  (0) 2021.04.14
profile

Zero to Hero

@Doljae

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!