문제 링크 : https://leetcode.com/problems/maximum-depth-of-binary-tree/
사실 문제 의도를 잘 모르겠는데..
# Definition for a binary tree node.
# 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 root is None:
return 0
return max(self.maxDepth(root.right),self.maxDepth((root.left)))+1
맨 아래노드(=leaf node)까지 내려간 뒤에 하나씩 올라오며 깊이를 세는 로직이다. 자식노드가 없는 리프노드까지 내려가면 자식노드를 파라미터로 전달할 때 0을 리턴하고, 해당 리프노드의 리턴값은 1이 된다.
리프노드가 최대 2개(문제 제목이 Binary Tree)이므로 왼쪽/오른쪽으로 나누어서 깊이를 계산하고 최댓값을 선정하여 리턴하면 최종적으로 최대 깊이가 나오게 된다.
빈 배열을 하나 선언해준다. 그러고 dfs함수를 만든다. 이때 왼쪽 탐색하고 값을 result에 대입하고 오른쪽 탐색하고 node가 None이 아닐 때까지 순회를 해준다.
Runtime: 64 ms, faster than 39.68% of Python3 online submissions for Maximum Depth of Binary Tree.
Memory Usage: 16.2 MB, less than 55.48% of Python3 online submissions for Maximum Depth of Binary Tree.