LeetCode/Minimum Depth of Binary Tree
[ h tps : // / ㅇ t 여기. 이 m / p 로 b ぇ ms / 미니무 m에서 pth ]
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7],

return its minimum depth = 2.
나무 깊이의 Maximum을 취하는 문제 은 있었지만, 이번에는 Minimum을 취하는 문제입니다.
max를 min으로 바꾸는 것만으로 OK…와는 가지 않습니다.
해답·해설
해법 1
기본적으로 recursive 함수를 정의하고 1 + min(self.minDepth(root.left), self.minDepth(root.right))에서 가장 얕은 나무의 깊이를 얻는 전략으로 좋습니다. 하지만 아래의 나무처럼 한쪽만 subtree가 없는 경우,

가장 얕은 나무의 깊이를 가져오면 0이 됩니다.The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. 을 추적한 다음 가장 얕은 나무의 깊이를 반환해야합니다.
즉 1 + max(self.minDepth(root.left), self.minDepth(root.right))를 취하는 조건 분기를 추가할 필요가 있다는 것입니다.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def minDepth(self, root: TreeNode) -> int:
if not root:
return 0
elif not root.left or not root.right:
return 1 + max(self.minDepth(root.left), self.minDepth(root.right))
else:
return 1 + min(self.minDepth(root.left), self.minDepth(root.right))
해법 2
Discussion 안에, 3 lines의 심플한 코드가 있었으므로 전재합니다.
class Solution:
def minDepth(self, root: TreeNode) -> int:
if not root: return 0
d = list(map(self.minDepth, (root.left, root.right)))
return 1 + (min(d) or max(d))
self.minDepth를 root.left, root.right에 적용하는 처리에서 map 함수를 사용하고 있네요.
하지만 아래 기사에서와 같이 map 함수를 적용하여 얻은 반복자를 목록으로 변환하는 과정에서 오버헤드가 발생하여 계산이 느려지는 것 같습니다.
실제로, LeetCode에의 submit를 몇번이나 해 보았던 체감에서는, map 함수를 사용하지 않는 것이 빨랐습니다.
[ htps // tgwk. 는 bぉ. jp/엔트리/2017/03/09/154314 ]
또한 마지막 return 1 + (min (d) or max (d))의 처리에 보충하면,
파이썬에서 (a or b)는 a가 존재하면 a, 존재하지 않으면 b를 반환합니다. (min(d) or max(d))는 min(d) > 0일 때 min(d), min(d) == 0일 때 max(d)를 반환합니다.
해법 1에서 설명한 것처럼, 한쪽만 subtree가 없는, 즉 min(d) == 0일 때에 존재하는 subtree를 따르는, 즉 1 + max(d)를 취하는 것 같은 처리가 되어 있습니다.
Reference
이 문제에 관하여(LeetCode/Minimum Depth of Binary Tree), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://qiita.com/mhiro216/items/51ab0719211e5464e7fc텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)