Skip to content
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
87 changes: 87 additions & 0 deletions 104. Maximum Depth of Binary Tree.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
1st

最大深度を求めるので再帰の DFS で解いた。
ノードの深さは最大 10^4 なので、デフォルトの再帰の設定だと`RecursionError`が発生するので気を付ける必要がある。
時間計算量:O(n)
空間計算量:O(n) 木がバランスしていれば O(logn)か

```python
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if root is None:
return 0

left_depth = self.maxDepth(root.left)
right_depth = self.maxDepth(root.right)

return max(left_depth, right_depth) + 1
```

2nd
1st とほぼおなじ。if not root に変えただけ。

```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
```

スタックを用いた DFS。
再帰と違いスタックオーバーフローを気にしなくてよい。

```python
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
tree_nodes = []
tree_nodes.append((root, 1))
max_depth = 0
while tree_nodes:
node, depth = tree_nodes.pop()
if node is None:
continue
max_depth = max(max_depth, depth)
if node.left:
tree_nodes.append((node.left, depth + 1))
if node.right:
tree_nodes.append((node.right, depth + 1))
return max_depth
```

BFS。
木がバランスしていても空間計算量が O(n)のため、今回のケースだと DFS のほうがより効率的になる可能性が高い。

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

BFS はいくつか書き方があるんですが、階層ごとにしたいときには、私は List 2つで作るのが好みです。
Yusan1234/arai60#1 (comment)
https://discord.com/channels/1084280443945353267/1201211204547383386/1219179255615717399

一つの変数に、2つの違う種類のものを入れておいて、その境界を個数で管理している
データの整合性が取れているということは、読んでいる人からすると全部読み終わらないと分からない

下は関係のあるようなないような読み物です。Queue を Stack で代用する話ですね。
https://cp-algorithms.com/data_structures/stack_queue_modification.html

```python
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
tree_nodes = deque([root])
depth = 0
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

while内でdepthのインクリメントを忘れています。

while tree_nodes:
level_size = len(tree_nodes)
for _ in range(level_size):
node = tree_nodes.popleft()
if node.left:
tree_nodes.append(node.left)
if node.right:
tree_nodes.append(node.right)
return depth
```

3rd

```python
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if root is None:
return 0

left_depth = self.maxDepth(root.left)
right_depth = self.maxDepth(root.right)

return max(left_depth, right_depth) + 1
```