문제
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.
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: 3
Example 2:
Input: root = [1,null,2]
Output: 2
Example 3:
Input: root = []
Output: 0
Example 4:
Input: root = [0]
Output: 1
Constraints:
- The number of nodes in the tree is in the range [0, 104].
- -100 <= Node.val <= 100
풀이
재귀함수를 사용하여 트리를 순회하면서 깊이를 측정한다.
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if root == None :
return 0
else :
left = 0
right = 0
if root.left != None :
left = self.maxDepth(root.left)
if root.right != None :
right = self.maxDepth(root.right)
return 1 + max(left, right)
'알고리즘 트레이닝 > LeetCode' 카테고리의 다른 글
66. Plus One (0) | 2021.03.04 |
---|---|
2. Add Two Numbers (0) | 2020.05.11 |
100. Same Tree (0) | 2020.05.11 |
88. Merge Sorted Array (0) | 2020.05.11 |
21. Merge Two Sorted Lists (0) | 2020.05.09 |