Skip to content

Conversation

@SuperHotDogCat
Copy link
Owner

node, depth = queue.popleft()
if not node.left and not node.right:
minimum_depth = depth
break

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ここでreturnしてしまって良いと思いました。

def minDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
minimum_depth = 0

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

BFSで解くのであれば、leaf nodeを見つけた段階でdepthを返してしまって良いので、minimum_depthは不要かと思います。

def minDepth(self, root: Optional[TreeNode]) -> int:
# 幅優先で良い
minimum_depth = 0
queue = deque([(root, 0)])
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

phase2, 3だと変えてるので違和感あったのかなと思いますが、(node, nodeの一つ上の深さ) の組をキューに入れているのは理解するの難しいなと思いました。

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

そうですね, phase1でわかりにくい+書くなら少しコメントを書く必要があると感じたのでphase2とphase3で変更しました

if node.right and node.left:
queue.append((node.right, depth + 1))
queue.append((node.left, depth + 1))
elif node.right is not None:
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(phase1のコードに突っ込み入れるのも野暮かもしれませんが) ここだけNoneを使って書いていて他は使ってないので違和感ありました。 elif node.right: で良さそうです

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ありがとうございます。その通りです...

Comment on lines +12 to +15
if node.left:
queue.append((node.left, depth + 1))
if node.right:
queue.append((node.right, depth + 1))
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

None であっても気にせずに queue につっこんで、出てきたやつを continue するという手もあります。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants