Skip to content
Open
Show file tree
Hide file tree
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
26 changes: 26 additions & 0 deletions 104-Maximum-Depth-of-Binary-Tree/note.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# 104. Maximum Depth of Binary Tree

https://leetcode.com/problems/maximum-depth-of-binary-tree/

## step1(まず通す)

深さ優先探索だと一番深いところにいつ当たるかわからないので、max_depth を持っておいて更新していく。

幅優先探索だと木なら同じ高さのノードを順番に見ていく形になるので最後に見たノードが一番深い。

ということで幅優先探索する。いつも (node, distance) のキューでやってたが、今回は階層ごとに見ていって一番深いところの深さを得るというのを素朴に表現してみる。

## step2(整形&他の人のコードを読む)

- https://github.com/hayashi-ay/leetcode/pull/22/changes
- Python では再帰が好まれない印象なので避けたが、木のような構造が再帰的なやつは再帰で書くととてもわかりやすい
- [浅井健一『プログラミングの基礎』(サイエンス社)](https://www.saiensu.co.jp/search/?isbn=978-4-7819-1160-1&y=2007#detail)(ちなみにこんな名前で OCaml。名著。)ではデータ構造の再帰的な定義と一対一で対応した再帰を「構造にしたがった再帰」と呼んでいるが、今回のようなものはまさにそう。
- 木の再帰的な定義:
- None は木である
- ある一つのノードがあってその子が全て木であるものは木である。
- この問題を解く再帰関数:
- None なら高さは 0 である
- ある一つのノードにおける高さはその子の高さの max に 1 を加えたものである。
- 今回は ノード数 <= 10 ^ 4 なので、再帰の深さは log 10 ^ 4 ~ 13 とかなので Python のリミット的にもスタックのサイズ的にも基本的に問題ない。

## step3(10分以内にさっとかける \* 3回)
29 changes: 29 additions & 0 deletions 104-Maximum-Depth-of-Binary-Tree/step1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
from typing import Optional


class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right


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

nodes = [root]
next_layer = []
depth = 0
while nodes:
depth += 1
for node in nodes:
if node.left is not None:
next_layer.append(node.left)
if node.right is not None:
next_layer.append(node.right)
nodes = next_layer
next_layer = []

return depth
15 changes: 15 additions & 0 deletions 104-Maximum-Depth-of-Binary-Tree/step2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
from typing import Optional


class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right


class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if root is None:
return 0
return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1
29 changes: 29 additions & 0 deletions 104-Maximum-Depth-of-Binary-Tree/step3.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
from typing import Optional


class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right


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

nodes = [root]
next_layer = []
depth = 0
while nodes:
depth += 1
for node in nodes:
if node.left is not None:
next_layer.append(node.left)
if node.right is not None:
next_layer.append(node.right)
nodes = next_layer
next_layer = []

return 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.

next_layerの初期化はまとめられそうです。

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

        nodes = [root]
        depth = 0
        while nodes:
            depth += 1
            next_layer = []
            for node in nodes:
                if node.left is not None:
                    next_layer.append(node.left)
                if node.right is not None:
                    next_layer.append(node.right)
            nodes = next_layer
            
        return depth

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.

ありがとうございます。
個人的には nodesnext_layer の初期化・更新はセットでやりたい感覚(今の階層 vs. 次の階層、という対の意識)があってこう書いたのですが h-masder さんの感覚だとどうですか?

nodes はループ中も一貫した意味を持つ名前なのに対して next_layer は while のループ一回ごとに完結して意味を持つのでループ内だけに存在してて欲しい(からまとめる)というのもわかります。

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

私としては、next_layer はループの中で毎回作るものというイメージがあるので、中で初期化しています。

とはいえ、このあたりは好みの問題で、どちらの書き方でもいいのかなと思っています。

感覚としては、「各ループの最初に next_layer を空にして使い始める」か、「ループの最後に次のループのために空にしておく(後片付けしておく)」かという違いで、どちらの考え方もよくわかります。

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.