Skip to content

617. Merge Two Binary Trees#23

Open
rimokem wants to merge 1 commit into
mainfrom
0617-merge-two-binary-trees
Open

617. Merge Two Binary Trees#23
rimokem wants to merge 1 commit into
mainfrom
0617-merge-two-binary-trees

Conversation

@rimokem
Copy link
Copy Markdown
Owner

@rimokem rimokem commented Apr 20, 2026

Comment thread 0617/memo.md
@@ -0,0 +1,113 @@
# 617. Merge Two Binary Trees
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

入力のノードを再利用するバージョンも書いたら良いと思います。

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

書いてみたところ、以下のようになりました。
入力ノードを再利用して再帰で書くと、かなりシンプルに書けるなと感じました。

class Solution:
    def mergeTrees(
        self, root1: Optional[TreeNode], root2: Optional[TreeNode]
    ) -> Optional[TreeNode]:
        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

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.

2 participants