Skip to content

Conversation

@skypenguins
Copy link
Owner

111. Minimum Depth of Binary Tree

次回予告: 112. Path Sum

@skypenguins skypenguins self-assigned this Jul 30, 2025
node = visited_node.popleft()
if node.left and node.right:
min_tree_depth += 1
if not node.left and not node.right:
Copy link

Choose a reason for hiding this comment

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

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:

Choose a reason for hiding this comment

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

この行でreturn 1をするのではなく、最後に左右のサブツリーの小さい方+1を返却することもできますね。

Choose a reason for hiding this comment

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

その場合87と89の条件をそれぞれ否定に変えてleftがnoneなら右側のサブツリーの深さ+1などにしないといけなさそうでした。

Copy link
Owner Author

Choose a reason for hiding this comment

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

以下のような感じですかね。(だいぶ変わってしまいましたが)

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])

Choose a reason for hiding this comment

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

visitedに対しての使い方がイメージに合わないなと思いました。
nodeと深さを格納しているnode_and_depthは分かりやすいと感じました。

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants