Conversation
| node = visited_node.popleft() | ||
| if node.left and node.right: | ||
| min_tree_depth += 1 | ||
| if not node.left and not node.right: |
There was a problem hiding this comment.
None であるかどうかをチェックする場合、 x is None と書いたほうが良いかもしれません。理由は、 x が何らかの状態のときに False として評価される場合、 not x と書くと、 None なのか False なのか分からないためです。
参考までにスタイルガイドへのリンクを貼ります。
https://google.github.io/styleguide/pyguide.html#2144-decision
上記のスタイルガイドは唯一絶対のルールではなく、複数あるスタイルガイドの一つに過ぎないということを念頭に置くことをお勧めします。また、所属するチームにより何が良いとされているかは変わります。自分の中で良い書き方の基準を持ちつつ、チームの平均的な書き方で書くことをお勧めいたします。
| if not root: | ||
| return 0 | ||
|
|
||
| if not root.left and not root.right: |
There was a problem hiding this comment.
この行でreturn 1をするのではなく、最後に左右のサブツリーの小さい方+1を返却することもできますね。
There was a problem hiding this comment.
その場合87と89の条件をそれぞれ否定に変えてleftがnoneなら右側のサブツリーの深さ+1などにしないといけなさそうでした。
There was a problem hiding this comment.
以下のような感じですかね。(だいぶ変わってしまいましたが)
class Solution:
def minDepth(self, root: Optional[TreeNode]) -> int:
if root is None:
return 0
left_depth = self.minDepth(root.left)
right_depth = self.minDepth(root.right)
if left_depth == 0 or right_depth == 0:
return max(left_depth, right_depth) + 1
return min(left_depth, right_depth) + 1| if not root: | ||
| return 0 | ||
|
|
||
| visited_node = deque([root]) |
There was a problem hiding this comment.
visitedに対しての使い方がイメージに合わないなと思いました。
nodeと深さを格納しているnode_and_depthは分かりやすいと感じました。
111. Minimum Depth of Binary Tree
次回予告: 112. Path Sum