-
Notifications
You must be signed in to change notification settings - Fork 0
Create Minimum_Depth_of_Binary_Tree.md #13
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: master
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| 一回目。答えを見た。 | ||
|
|
||
| ```py | ||
| class Solution: | ||
| def minDepth(self, root: Optional[TreeNode]) -> int: | ||
| if root is None: | ||
| return 0 | ||
|
|
||
| queue = [(root, 1)] | ||
| while queue: | ||
| node, depth = queue.pop(0) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. list() の pop(0) を呼び出すと、それより後の要素のデータの移動が行われるため、効率的に処理できません。https://github.com/python/cpython/blob/main/Objects/listobject.c#L1511 https://docs.python.org/ja/3/tutorial/datastructures.html#using-lists-as-queues
代わりに collections.deque を使うことをお勧めいたします。
Owner
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 知りませんでした!ありがとうございます! |
||
| if node.left is None and node.right is None: | ||
| return depth | ||
| if node.left: | ||
| queue.append((node.left, depth + 1)) | ||
| if node.right: | ||
| queue.append((node.right, depth + 1)) | ||
| ``` | ||
|
|
||
| 2回目と3回目。子ノードが None かどうかの判定は(1つ目と2, 3個目で)そろえたほうがよいと判断した。 | ||
|
|
||
| ```py | ||
| class Solution: | ||
| def minDepth(self, root: Optional[TreeNode]) -> int: | ||
| if root is None: | ||
| return 0 | ||
|
|
||
| queue = [(root, 1)] | ||
| while queue: | ||
| node, depth = queue.pop(0) | ||
| if node.left is None and node.right is None: | ||
| return depth | ||
| if node.left is not None: | ||
| queue.append((node.left, depth + 1)) | ||
| if node.right is not None: | ||
| queue.append((node.right, depth + 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.
再帰を使った解法も書いてみるとよいかもしれません。
複数の書き方ができるようにしておき、状況に応じて適切な書き方を選んでかけるようになっていると理想的だと思います。
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.
念のための確認ですが、BFSでもですか?DFSならわかりますが...
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.
DFS のほうです。