Skip to content

104. Maximum Depth of Binary Tree #21

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions 104/104.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
## 何も見ずに解いてみる

```python
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
queue = deque()
def append_if_not_none(node, depth):
if node is not None:
queue.append((node, depth))
depth = 0

Choose a reason for hiding this comment

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

ここら辺にqueueの初期化があった方が分かりやすいと思いました。今回はヘルパー関数が短いので問題なさそうですが。

Copy link
Owner Author

Choose a reason for hiding this comment

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

上から読んでいったときにヘルパー関数の中でまだ導入されてない変数を操作することになるのでヘルパー変数の前に置く方がいいかなと思ったんですが、変数の定義はあとでも良いという人も多いんですかね? 👀

append_if_not_none(root, depth + 1)
while queue:
node, depth = queue.popleft()
append_if_not_none(node.left, depth + 1)
append_if_not_none(node.right, depth + 1)

Choose a reason for hiding this comment

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

個人的には append_if_exist などもありかなと感じました。

return depth
```

大人しくif root is None: return 0を最初に入れてしまったほうが読みやすかったかも

## 色々調べてみる

https://github.com/tokuhirat/LeetCode/pull/21/files
https://github.com/shintaro1993/arai60/pull/25/files
https://github.com/hayashi-ay/leetcode/pull/22/files
https://github.com/rossy0213/leetcode/pull/10/files

再帰を使う選択肢は思い浮かばなかった・・・選択肢の一つにはしておきたい。
next_nodesのリストを作っていって次のループに入る前にnodesに代入するやり方とtupleなどで深さも一緒に保存しておくやり方、どっちのが読みやすいですかね?
Copy link

Choose a reason for hiding this comment

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

私はタプルのほうが趣味ですね。どちらでもいいのではないでしょうか。


## 最終コード

```python
from collections import deque

class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
queue = deque([(root, 1)])
while queue:
node, depth = queue.popleft()
if node.left is not None:
queue.append((node.left, depth + 1))
if node.right is not None:
queue.append((node.right, depth + 1))
return depth
```

Choose a reason for hiding this comment

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

読みやすかったです。Step2で見かけた再帰を使う方法も何も見ずに再現できるかを試してみると勉強になると思いました。