104. Maximum Depth of Binary Tree
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
stk = [(root, 1)]
answer = 1
while stk:
root, depth = stk.pop()
answer = max(answer, depth)
if root.left:
stk.append((root.left, depth + 1))
if root.right:
stk.append((root.right, depth + 1))
return answer
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
def dfs(node: Optional[TreeNode], depth: int) -> int:
if not node:
return depth
return max(dfs(node.left, depth + 1), dfs(node.right, depth + 1))
return dfs(root, 0)
디음 코드와 같이 중첩 함수를 사용하지 않는 방법도 있다.
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
left_depth = self.maxDepth(root.left)
right_depth = self.maxDepth(root.right)
return max(left_depth, right_depth) + 1