[알고리즘/leetcode] Maximum Depth of Binary Tree(python)

유현민·2022년 8월 20일
0

알고리즘

목록 보기
230/253


재귀를 이용해서 문제를 해결했다.

이진 트리이기 때문에 두개로 나누어서 재귀를 실행했고 자식 노드가 없는 리프 노트까지 내려가면 1을 더해주었다.

최종적으로 왼쪽, 오른쪽 값 중 가장 큰 값을 리턴해줌

class Solution:
    def maxDepth(self, root):
        return self.dfs(root)

    def dfs(self, root):
        if not root:
            return 0
        l = self.dfs(root.left) + 1
        r = self.dfs(root.right) + 1

        return max(l, r)
profile
smilegate megaport infra

0개의 댓글