소피it블로그
[LeetCode] 104번 Maximum Depth of Binary Tree 문제 풀이 (파이썬) 본문
https://leetcode.com/problems/maximum-depth-of-binary-tree/
Maximum Depth of Binary Tree - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
재귀적으로 풀 수 있었다. 다이나믹 프로그래밍의 원리를 이용해서, 특정 노드에서의 최대 깊이는 자식 노드의 최대 깊이에 1을 더한 것이라는 점에 착안하여 풀었다. 다만 재귀적으로 푸는 과정에서 바로 max값을 구해주었기 때문에 메모이제이션은 사용하지 않았다.
BFS로 푼 풀이들도 있는 것 같은데 다시 풀어봐도 괜찮을 듯.
# 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:
def get_depth(node):
while node: # 노드가 null이 아닌 경우
if not node.left and not node.right: # 단말 노드인 경우
return 1
# 자식 노드들의 최고 깊이에 1을 더한 값을 리턴함
return max(get_depth(node.left), get_depth(node.right)) + 1
return 0 # 노드가 null인 경우에는 0 반환
return get_depth(root) # return 빼먹을 경우 다 풀어놓고 오답 판정 받을 수 있으니 꼼꼼히 하자
'CS > 알고리즘 문제풀이' 카테고리의 다른 글
[LeetCode] 739번 Daily Temperatures 문제 풀이 (파이썬) 그리고 enumerate에 대한 고찰 (0) | 2022.10.06 |
---|---|
[LeetCode] 70번 Climbing Stairs 문제 풀이 (파이썬) (0) | 2022.10.03 |
[LeetCode] 3번 Longest Substring Without Repeating Characters 문제 풀이 (파이썬) (0) | 2022.10.03 |
[이코테] 효율적인 화폐 구성 문제 풀이 (파이썬) (0) | 2022.10.02 |
[백준] 11053번 가장 긴 증가하는 부분 수열 문제 풀이 (파이썬) (1) | 2022.10.02 |