Given the root of a binary tree, return its maximum depth. A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Constraints: 1. The number of nodes in the tree is in the range[0, 104]. 2. -100 <= Node.val <= 100
# 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 = rightfrom collections import deque
classSolution:defmaxDepth(self, root: TreeNode) -> int:
level = 0ifnot root:
return0
q = deque([root])
while q:
level += 1for _ inrange(len(q)):
node = q.popleft()
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
return level
이번 문제는 트리의 최대 깊이를 찾는 문제로 BST를 활용해야 했다. 처음엔 모든 노드를 훑으면서 같은 층(깊이)에 있는 노드가 아니라면 level이란 변수에 1을 더하는 식으로 했다.
같은 층에 있는 노드에 대해선 1) queue에 자식노드를 추가하고, 2) 이 자식노드들의 자식노드들이 추가될 때까지 for문을 돌렸다. for문을 빠져나올 때(=다음 층의 노드들의 차례가 왔을 때) 비로소 level += 1을 해주었다.
모든 노드에 대해서 queue에 넣고 빼고 하는 작업이 꼭 필요할까 의문을 품으며 다른 사람들의 코드를 함께 살펴봤다. 아래는 재귀구조를 통해 문제를 해결한 매우 깔끔한 코드이다.