diff --git a/104. Maximum Depth of Binary Tree.md b/104. Maximum Depth of Binary Tree.md new file mode 100644 index 0000000..5da9e43 --- /dev/null +++ b/104. Maximum Depth of Binary Tree.md @@ -0,0 +1,94 @@ +URL: https://leetcode.com/problems/maximum-depth-of-binary-tree/description/ + +# Step 1 + +- 実装時間: 5分 +- ノード数をnとして +- 時間計算量: O(n) +- 空間計算量: O(n) + +```python +class Solution: + def maxDepth(self, root: Optional[TreeNode]) -> int: + max_depth = 0 + nodes_and_depths = [(root, 1)] + while nodes_and_depths: + node, depth = nodes_and_depths.pop() + if node is None: + continue + max_depth = max(max_depth, depth) + nodes_and_depths.append((node.left, depth + 1)) + nodes_and_depths.append((node.right, depth + 1)) + return max_depth +``` + +leetcodeの活動を通して、ループへの慣れが出てきた。 + +# Step 2 + +- 参考にしたURL + - https://github.com/colorbox/leetcode/pull/35 + - https://github.com/tarinaihitori/leetcode/pull/21 + - https://github.com/haniwachann/leetcode/pull/4 + - https://github.com/rihib/leetcode/pull/41 + - https://github.com/hroc135/leetcode/pull/20 + - https://github.com/seal-azarashi/leetcode/pull/20 + - https://github.com/goto-untrapped/Arai60/pull/45 + - https://github.com/Ryotaro25/leetcode_first60/pull/23 + - https://github.com/kazukiii/leetcode/pull/22 + - https://github.com/NobukiFukui/Grind75-ProgrammingTraining/pull/38 + - https://github.com/Yoshiki-Iwasa/Arai60/pull/23 + - https://github.com/SuperHotDogCat/coding-interview/pull/34 + - https://github.com/fhiyo/leetcode/pull/23 + - https://github.com/nittoco/leetcode/pull/14 + +- バリエーション + - 上から/下から + - stackじゃなくてqueueにすると、maxでの比較が不要になる。 + - ループ/再帰関数 + - stackにdepthも入れる/階層ごとに二重ループを回す + - > 階層ごとにしたいときには、私は List 2つで作るのが好みです。 + - https://github.com/tarinaihitori/leetcode/pull/21/files#r1859073373 + +- > 古い C の流儀で、変数は上の方にまとめて宣言というのはありますが、現代的ではないかと思います。 + - https://github.com/haniwachann/leetcode/pull/4/files#r1845319724a + +- > 私は、比較的、stack や queue という名前は状況次第で許容側です。 + - https://github.com/rihib/leetcode/pull/41/files#r1782885611 + - `nodes_and_depths`という変数名も`node_and_depth_stack`にすると使われ方も示せてよさそう + +```python +class Solution: + def maxDepth(self, root: Optional[TreeNode]) -> int: + max_depth = 0 + node_and_depth_queue = deque([(root, 1)]) + while node_and_depth_queue: + node, depth = node_and_depth_queue.popleft() + if node is None: + continue + max_depth = depth + node_and_depth_queue.append((node.left, depth + 1)) + node_and_depth_queue.append((node.right, depth + 1)) + return max_depth +``` + +# Step 3 + +- ノード数をnとして + - 時間計算量: O(n) + - 空間計算量: O(n) + +```python +class Solution: + def maxDepth(self, root: Optional[TreeNode]) -> int: + max_depth = 0 + node_and_depth_queue = deque([(root, 1)]) + while node_and_depth_queue: + node, depth = node_and_depth_queue.popleft() + if node is None: + continue + max_depth = depth + node_and_depth_queue.append((node.left, depth + 1)) + node_and_depth_queue.append((node.right, depth + 1)) + return max_depth +```