Skip to content

Conversation

garunitule
Copy link
Owner

return root1

return TreeNode(
val = root1.val + root2.val,

Choose a reason for hiding this comment

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

nit: キーワード引数を渡す際、"="の周りにスペースを用いない形の方がよく見ますね。

https://peps.python.org/pep-0008/#other-recommendations

Don’t use spaces around the = sign when used to indicate a keyword argument, or when used to indicate a default value for an unannotated function parameter:

# Correct:
def complex(real, imag=0.0):
    return magic(r=real, i=imag)
# Wrong:
def complex(real, imag = 0.0):
    return magic(r = real, i = imag)

```

https://discord.com/channels/1084280443945353267/1233603535862628432/1277243820118900847
破壊的か非破壊的かは賛否ありそうだが、あるときは破壊的であるときは非破壊的なのは避けたい

Choose a reason for hiding this comment

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

破壊的・非破壊的という言葉にあまり馴染みがないのですが、入力を変更しているかどうか、という意味なら入力の木に対して変更を加えているわけではないので、step 1の方法は非破壊的(副作用がない?)ということになるのでしょうか...?しかし、呼び出し側から考えると、返ってきた木に対して変更を加えたら入力に与えた木にも変更が加わり、少し驚くかもしれませんね。

さておき、ご自身でもご指摘の通り、私もstep 1の解法を見た際、新しくTreeNodeを作っている部分ではまるきり新しい木を作ろうとしているように見える一方で、ある部分では入力の木のNodeを流用していてややちぐはぐな印象を覚えました。入力に使った木を流用して、以降root1, root2は使えないとするなら

class Solution:
    def mergeTrees(self, root1: TreeNode | None, root2: TreeNode | None) -> TreeNode | None:
        """merge the second tree to the first"""
        if root1 is None:
            return root2
        if root2 is None:
            return root1

        root1.val += root2.val
        root1.left = self.mergeTrees(root1.left, root2.left)
        root1.right = self.mergeTrees(root1.right, root2.right)
        return root1

完全に独立させたいなら

import copy


class Solution:
    def mergeTrees(self, root1: TreeNode | None, root2: TreeNode | None) -> TreeNode | None:
        if root1 is None:
            return copy.deepcopy(root2)
        if root2 is None:
            return copy.deepcopy(root1)

        return TreeNode(
            val=root1.val + root2.val,
            left=self.mergeTrees(root1.left, root2.left),
            right=self.mergeTrees(root1.right, root2.right),
        )

とした方が扱いやすいと思います。

Copy link
Owner Author

Choose a reason for hiding this comment

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

たしかに入力に変更を加えないようにするにはdeepcopyのほうが良いですね

```python
class Solution:
def mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]:
roots = list(filter(None, [root1, root2]))

Choose a reason for hiding this comment

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

以前、野田さんがTwitter(新X)でアンケートを取っていたのを思い出しました。
https://x.com/nodchip/status/1932263139762229448
私も、わかるといえばわかるのですが、頻繁に見ることのない書き方だなと感じます。多少長くなってもif文の方が、ぱっと見でもわかりやすいかもしれません。参考まで。


```python
class Solution:
def mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]:
Copy link

@huyfififi huyfififi Aug 6, 2025

Choose a reason for hiding this comment

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

このiterativeな解法も理解できますが、直感的に考えると、あるNodeを作り終えるには、先にその下のNodes (left, right)を作り、そこに向けてreferencesを貼る作業をしなければならない、と考えると、top-downよりも、bottom-upの方法 (e.g., step 1の再帰) が自然で誰しも思いつきやすいのではないか、と想像します。

# step2: 30分
## 他の人のPRやコメントを踏まえて実装
leetcodeの解法を見た
たしかに、root is None and root2 is Noneの分岐は不要だな
Copy link

Choose a reason for hiding this comment

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

root1 と root2 が両方とも None の場合、

if root1 is None:
    return root2

が None を返すのですが、ややパズルに感じるため、明示的に書いたほうが読みやすくなるかもしれません。

nodes_to_merge.append((dst_node.right, rights))

return merged_tree
```

Choose a reason for hiding this comment

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

すでにコメントがついている点以外は問題ないと思いました。

@garunitule garunitule merged commit fe88be8 into main Aug 9, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants