Online Judge/LeetCode
[LeetCode][Python] 104. Maximum Depth of Binary Tree
vince joe
2024. 9. 16. 23:31
- 문제 링크: https://leetcode.com/problems/maximum-depth-of-binary-tree/
- 난이도: Easy
binary tree의 max depth를 구하는 문제
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
def bt(curr_depth: int, node: TreeNode) -> int:
# leaf
if not node.left and not node.right:
return curr_depth
max_depth = 0
if node.left:
max_depth = max(max_depth, bt(curr_depth+1, node.left))
if node.right:
max_depth = max(max_depth, bt(curr_depth+1, node.right))
return max_depth
return bt(1, root)
반응형