【Arai60】22問目 111_Minimum Depth of Binary Tree#22
Conversation
| node_queue.append((node.left, depth + 1)) | ||
| if node.right: | ||
| node_queue.append((node.right, depth + 1)) | ||
| min_node_num = depth + 1 |
There was a problem hiding this comment.
あくまで C++ をメインで使っている人間の印象なのですが、ループの中で定義した変数をループの外で参照している点に違和感を感じました。 break するのではなく、直接 return depth + 1 してしまったほうが、個人的には直感的に思いました。
また、 min_node_num というフレーズですと、 the number of nodes along the shortest path の部分が伝わらないように思いました。関数名と被ってやや微妙ですが、 min_depth でも良いように思いました。
There was a problem hiding this comment.
ループ内で定義した変数は、ループ内のローカル変数といったような意識で使ってみます。
意識したことなかったので、気にしてみます。
| # DFS | ||
| class Solution: | ||
| def minDepth(self, root: Optional[TreeNode]) -> int: | ||
| def search_min_depth(node): |
There was a problem hiding this comment.
好みの問題なのですが、 minDepth() をそのまま使って再帰しても良いと思いました。
There was a problem hiding this comment.
minDepth() をそのまま使い、少しコードをすっきりさせることができました。
class Solution:
def minDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
if not root.left and not root.right:
return 1
min_depth = sys.maxsize
if root.left:
min_depth = min(min_depth, self.minDepth(root.left) + 1)
if root.right:
min_depth = min(min_depth, self.minDepth(root.right) + 1)
return min_depth
| def search_min_depth(node): | ||
| if not node.left and not node.right: | ||
| return 0 | ||
| left_depth = float(inf) |
There was a problem hiding this comment.
depth を求めようとしているにもかかわらず、 float を使用している点に違和感を感じました。
if not node.left and not node.right:
return 0
elif node.left:
return search_min_depth(node.right) + 1
elif node.right:
return search_min_depth(node.left) + 1
else:
min(search_min_depth(node.left), search_min_depth(node.right)) + 1
あたりでいかがでしょうか?
There was a problem hiding this comment.
[2,null,3,null,4,null,5,null,6] のパターンで 1を出力するとWrong Answerになってしまいます。
このケースに対応に良い方法が思いつかなかったため、min_depthの初期値をmaxsizeにしていました。
| node_depth_stack.append((node.right, depth + 1)) | ||
| if node.left: | ||
| node_depth_stack.append((node.left, depth + 1)) | ||
| min_node_num = min_depth + 1 |
hayashi-ay
left a comment
There was a problem hiding this comment.
特段気になるところはなかったです。強いていうならdepthの解釈。
| def search_min_depth(node): | ||
| if not node.left and not node.right: | ||
| return 0 | ||
| min_depth = sys.maxsize |
There was a problem hiding this comment.
C言語でいうUINT_MAXみたいな感じなんですね。あまり見慣れないですが選択肢としては良いんじゃないかなと思います。
問題
https://leetcode.com/problems/minimum-depth-of-binary-tree/