-
Notifications
You must be signed in to change notification settings - Fork 0
111. Minimum Depth of Binary Tree #16
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
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.
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: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
この行でreturn 1をするのではなく、最後に左右のサブツリーの小さい方+1を返却することもできますね。
There was a problem hiding this comment.
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などにしないといけなさそうでした。
There was a problem hiding this comment.
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]) |
There was a problem hiding this comment.
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は分かりやすいと感じました。
111. Minimum Depth of Binary Tree
次回予告: 112. Path Sum