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

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

## Comments

### step1

* 最初 `SolutionAC` の方で書いていたんだけど、これだと、(None, 1) のような要素が append されるので、なんか None に対して depth がついているの嫌な気がした。ので、`SolutionRuntimeError` に書き直した。
* よく考えると、root が None のケースを考慮していなくて Runtime Error。その後すぐに `SolutionAC` に書き直した。4:50 くらい。
* 大雑把に DFS、BFS を考えていて、再帰で書こうかと思ったのだが、再帰で書くときに depth の引数渡すのがなんとなく面倒だったのと、10^4 の制約でデフォルトの recursion limit 超える気がしたので iterative DFS にした。
* > The number of nodes in the tree is in the range [0, 104].

### step2

* https://github.com/nittoco/leetcode/pull/14/files
* https://discord.com/channels/1084280443945353267/1227073733844406343/1236235351140339742
* 私の方法は上から配る方だと思うが、概念として下から戻す方法が存在するのはわかるものの、今回どうやってやるのかよくわからない。このへん読んでみたが、結局なにをどうしているのかよくわからん…。一旦次に進む。
Copy link

Choose a reason for hiding this comment

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

先に進んでもいいかもしれません。一応、こちらに(別の問題ですが) Python のバージョンがあるので、これをみたらやろうとしていること分かるかもしれません。
potrue/leetcode#22 (comment)

Copy link
Owner Author

Choose a reason for hiding this comment

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

一応機械的に namedtuple で書き直してみましたが、結局あまりよくわかりませんでした。一旦先に進んで、どこかで戻ってみようかと思います… (return_value, left_value, right_value が何なのかすらわかっていない)。

class Solution:
    def minDepth(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0
            
        StackEntry = namedtuple('StackEntry', ['node', 'depth', 'return_value', 'left_value', 'right_value'])
        result = []
        stack = [StackEntry(root, 1, result, [], [])]
        while stack:
            node, depth, return_value, left_value, right_value = stack[-1]
            if node.left is not None and not left_value:
                stack.append(StackEntry(node.left, depth + 1, left_value, [], []))
                continue
            if node.right is not None and not right_value:
                stack.append(StackEntry(node.right, depth + 1, right_value, [], []))
                continue
            if not left_value and not right_value:
                min_depth = depth
            else:
                min_depth = min(value[0] for value in (left_value, right_value) if value)
            return_value.append(min_depth)
            stack.pop()
        return result[0]

Copy link
Owner Author

Choose a reason for hiding this comment

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

ここでの議論が参考になりそうなので記録しておきます。

https://github.com/ryosuketc/leetcode_arai60/pull/23/files#r2122113958

* https://discord.com/channels/1084280443945353267/1227073733844406343/1236695050902048899
* というかそもそも下から戻す再帰だいぶ苦手かも。
* > 訪れているかの判定を次の再帰に任せた場合、やや処理速度が落ちる点は気にしたほうが良いと思います。理由は、関数の呼び出しが、一般的に、コストがかかる処理だからです。個人的には再帰関数呼び出しの前に判定したほうが良いと思います。
* https://github.com/sakupan102/arai60-practice/pull/22#discussion_r1590605423
* これだと、`SolutionRuntimeError` の冒頭に `if root is None` を足せば動く
* 感覚として、個人的には再帰で書くより stack で iterative に書くほうが好きらしい。

### step3

* step2 で、これといっては直したいところもなかったので、一旦何回か書いてみて馴染まないところがあるか考えることにした。
* 1:10 -> 1:10 (特に変化がないので打ち切り)
28 changes: 28 additions & 0 deletions 104_maximum_depth_of_binary_tree/step1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
class SolutionRuntimeError:
def maxDepth(self, root: Optional[TreeNode]) -> int:
max_depth = 0
stack = [(root, 1)]
while stack:
node, depth = stack.pop()
max_depth = max(max_depth, depth)
if node.left is not None:
stack.append((node.left, depth + 1))
if node.right is not None:
stack.append((node.right, depth + 1))

return max_depth


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

return max_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 @@
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if root is None:
return 0
max_depth = 0
stack = [(root, 1)]
while stack:
node, depth = stack.pop()
max_depth = max(max_depth, depth)
if node.left is not None:
stack.append((node.left, depth + 1))
if node.right is not None:
stack.append((node.right, depth + 1))

return max_depth
21 changes: 21 additions & 0 deletions 104_maximum_depth_of_binary_tree/step3.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Definition for a binary tree node.
# 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:
stack = [(root, 1)]

Choose a reason for hiding this comment

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

nodes_and_depthsなどとしてもいい気がします

max_depth = 0

while stack:
node, depth = stack.pop()
if node is None:
continue
max_depth = max(max_depth, depth)
stack.append((node.left, depth + 1))
stack.append((node.right, depth + 1))

return max_depth

Choose a reason for hiding this comment

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

特に問題ないと思います。
再帰への書き換え、queueを使う/使わないBFS等の実装もありました