From 53c10627d0099fffe4c059ee82e0f50288651b6f Mon Sep 17 00:00:00 2001 From: mike <59136831+Mike0121@users.noreply.github.com> Date: Thu, 2 May 2024 01:07:31 +0900 Subject: [PATCH] 104. Maximum Depth of Binary Tree.md https://leetcode.com/problems/maximum-depth-of-binary-tree/description/?envType=list&envId=rbx9vwti --- .../104. Maximum Depth of Binary Tree.md" | 94 +++++++++++++++++++ 1 file changed, 94 insertions(+) create mode 100644 "\347\253\266\346\212\200\343\203\227\343\203\255\345\260\261\346\264\273\351\203\250PR\347\224\250/104. Maximum Depth of Binary Tree.md" diff --git "a/\347\253\266\346\212\200\343\203\227\343\203\255\345\260\261\346\264\273\351\203\250PR\347\224\250/104. Maximum Depth of Binary Tree.md" "b/\347\253\266\346\212\200\343\203\227\343\203\255\345\260\261\346\264\273\351\203\250PR\347\224\250/104. Maximum Depth of Binary Tree.md" new file mode 100644 index 0000000..d9d07b6 --- /dev/null +++ "b/\347\253\266\346\212\200\343\203\227\343\203\255\345\260\261\346\264\273\351\203\250PR\347\224\250/104. Maximum Depth of Binary Tree.md" @@ -0,0 +1,94 @@ + +### 1回目 (再帰(DFS)) +時間計算量: O(N) +空間計算量: O(N) +N: ノード数 + +```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 +``` + +### 1~3回目 (スタック/BFS) +時間計算量: O(N) +空間計算量: O(N) +N: ノード数 + +どのように各ルートの最大の深さをキープするべきかを考えて詰まった。 +(悩み中のコード消してしまいした、今後どこがわからなかったを明確化するために残すようにします。) +BFSをすれば良いことに気がつけず、while文中でfor文を回す発想に至らなかった。 + +### 1回目 +この方法はすこし違和感を感じた。特に、```node_stack = next_nodes```がやや無理矢理な気がした。 + +```python +class Solution: + def maxDepth(self, root: Optional[TreeNode]) -> int: + if not root: + return 0 + node_stack = [root] + max_depth = 0 + + while node_stack: + max_depth += 1 + next_nodes = [] + for node in node_stack: + if node.left: + next_nodes.append(node.left) + if node.right: + next_nodes.append(node.right) + node_stack = next_nodes + + return max_depth +``` + +### 2回目 +BFSの発想を元に、左に行くor右にいく→max_depthを都度比較→すべてが空になるまで幅優先で進んでいく。方法が良いと感じた。 +(追記: ahayshiさんとOdaさんのやりとりにありました。) + +```python +def maxDepth(self, root: Optional[TreeNode]) -> int: + if not root: + return 0 + node_stack = [(root, 1)] + max_depth = 1 + + while node_stack: + node, depth = node_stack.pop() + max_depth = max(max_depth, depth) + + if node.left: + node_stack.append((node.left, depth + 1)) + if node.right: + node_stack.append((node.right, depth + 1)) + return max_depth +``` + +2回目の```max_depth = 1```は少し変な感じがしたので修正。 + +### 3回目 +```python +class Solution: + def maxDepth(self, root: Optional[TreeNode]) -> int: + if not root: + return 0 + + node_stack= [(root, 1)] + max_depth = 0 + + while node_stack: + node, depth = node_stack.pop() + max_depth = max(max_depth, depth) + + if node.left: + node_stack.append((node.left, depth + 1)) + if node.right: + node_stack.append((node.right, depth + 1)) + + return max_depth +```