Skip to content

Conversation

@skypenguins
Copy link
Owner

104. Maximum Depth of Binary Tree

次回予告: 108. Convert Sorted Array to Binary Search Tree

@skypenguins skypenguins self-assigned this Jul 20, 2025
fix typo
while visited_nodes:
tree_depth += 1

for _ in range(len(visited_nodes)):
Copy link

Choose a reason for hiding this comment

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

直前の層のノード数だけループを回し、 1 層ずつ処理するという書き方は、あまり直感的ではないように思います。 deque を 2 つ用意して入れ替えるか、 deque の要素に高さも一緒に格納してあげたほうが直感的に感じます。

Copy link
Owner Author

Choose a reason for hiding this comment

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

以下のように修正してみました。

  • 2つのdequeを使う方法(BFS)
class Solution:
    def maxDepth(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0
        
        current_level = deque([root])
        next_level = deque()
        tree_depth = 0
        
        while current_level:
            tree_depth += 1
            # 現在の階層のノードを処理
            while current_level:
                node = current_level.popleft()
                if node.left:
                    next_level.append(node.left)
                if node.right:
                    next_level.append(node.right)
            
            # 次の階層に移動(dequeを入れ替え)
            current_level, next_level = next_level, current_level
        
        return tree_depth
  • dequeに高さの情報を入れる方法(BFS)
class Solution:
    def maxDepth(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0
        
        # (ノード, 深さ)のタプルをキューに格納
        node_and_depth = deque([(root, 1)])
        max_depth = 0
        
        while node_and_depth:
            node, depth = node_and_depth.popleft()
            max_depth = max(max_depth, depth)
            
            if node.left:
                node_and_depth.append((node.left, depth + 1))
            if node.right:
                node_and_depth.append((node.right, depth + 1))
        
        return max_depth

return 0

node = root
visited_nodes = deque([node])

Choose a reason for hiding this comment

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

この辺りの変数名にもう少し時間を使ってもよいと思います。visited_nodesと書くと訪れたノードが全部入っているように感じますが、実際はpopしているので違和感を感じました。

class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
max_depth = 0
def dive_into_leaf(node, depth):

Choose a reason for hiding this comment

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

関数名から何が返ってくるか処理が想像できませんでした。update_max_depthとかの方が分かりやすいと思いました。

dive_into_leaf(root, 1)
return max_depth
```
- スタックによるDFS・下から走査するボトムアップ方式
Copy link
Owner Author

Choose a reason for hiding this comment

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

同じスタックDFSかつボトムアップ走査でフラグを使わないパターン・辞書でノードごとの深さを管理してボトムアップにする方法もある

  • フラグを使わないパターン
class Solution:
    def maxDepth(self, root: Optional[TreeNode]) -> int:
        res_depth_ref = [None]
        # (node, ret_depth_ref, left_depth_ref, right_depth_ref)
        stack = [(root, res_depth_ref, [None], [None])] 
        while stack:
            node, ret_depth_ref, left_depth_ref, right_depth_ref = stack[-1]
            if not node:
                ret_depth_ref[0] = 0
                stack.pop()
                continue
            if left_depth_ref[0] is None:
                stack.append((node.left, left_depth_ref, [None], [None]))
                stack.append((node.right, right_depth_ref, [None], [None]))
                continue
            ret_depth_ref[0] = max(left_depth_ref[0], right_depth_ref[0]) + 1
            stack.pop()
        return res_depth_ref[0]
  • 辞書でノードごとの深さを管理するパターン
def maxDepth(self, root: Optional[TreeNode]) -> int:
    if not root:
        return 0
    
    stack = []
    depths = {}  # ノードごとの深さを記録
    node = root
    
    while stack or node:
        if node:
            stack.append(node)
            node = node.left
        else:
            node = stack.pop()
            left_depth = depths.get(node.left, 0)
            right_depth = depths.get(node.right, 0)
            depths[node] = max(left_depth, right_depth) + 1
            node = node.right
    
    return depths[root]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants