Skip to content
Merged
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
94 changes: 94 additions & 0 deletions 競技プロ就活部PR用/104. Maximum Depth of Binary Tree.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@

### 1回目 (再帰(DFS))
時間計算量: O(N)
空間計算量: O(N)
N: ノード数

```python
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
left_depth = self.maxDepth(root.left)
right_depth = self.maxDepth(root.right)
return max(left_depth, right_depth) + 1
```

### 1~3回目 (スタック/BFS)
時間計算量: O(N)
空間計算量: O(N)
N: ノード数

どのように各ルートの最大の深さをキープするべきかを考えて詰まった。
(悩み中のコード消してしまいした、今後どこがわからなかったを明確化するために残すようにします。)
BFSをすれば良いことに気がつけず、while文中でfor文を回す発想に至らなかった。

### 1回目
この方法はすこし違和感を感じた。特に、```node_stack = next_nodes```がやや無理矢理な気がした。

```python
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
node_stack = [root]
max_depth = 0

while node_stack:
max_depth += 1
next_nodes = []
for node in node_stack:
if node.left:
next_nodes.append(node.left)
if node.right:
next_nodes.append(node.right)
node_stack = next_nodes

return max_depth
```

### 2回目
BFSの発想を元に、左に行くor右にいく→max_depthを都度比較→すべてが空になるまで幅優先で進んでいく。方法が良いと感じた。
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

2回目の解法は普通にPreorderなDFSじゃないですか?

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

ご指摘のとおりですね。DFSでした。
BFSにするには、.pop(0)ですね。細かいところまで見て頂いてありがとうございます。

(追記: ahayshiさんとOdaさんのやりとりにありました。)

```python
def maxDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
node_stack = [(root, 1)]
max_depth = 1

while node_stack:
node, depth = node_stack.pop()
max_depth = max(max_depth, depth)

if node.left:
node_stack.append((node.left, depth + 1))
if node.right:
node_stack.append((node.right, depth + 1))
Comment on lines +65 to +68
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

教科書的なPreorderのDFSだと左側のノードから見ると思うので、node_stackに追加する順番が逆の方が個人的には好みです。

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

なるほどです。こちらも参考になります。確かにその方が良いですね。
ありがとうございます。

return max_depth
```

2回目の```max_depth = 1```は少し変な感じがしたので修正。

### 3回目
```python
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0

node_stack= [(root, 1)]
max_depth = 0

while node_stack:
node, depth = node_stack.pop()
max_depth = max(max_depth, depth)

if node.left:
node_stack.append((node.left, depth + 1))
if node.right:
node_stack.append((node.right, depth + 1))

return max_depth
```