diff --git a/104/104.md b/104/104.md new file mode 100644 index 0000000..c474ea0 --- /dev/null +++ b/104/104.md @@ -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 + 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) + 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などで深さも一緒に保存しておくやり方、どっちのが読みやすいですかね? + +## 最終コード + +```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 +```