Skip to content

617. Merge Two Binary Trees#22

Open
hemispherium wants to merge 2 commits into
mainfrom
0617-merge-two-binary-trees
Open

617. Merge Two Binary Trees#22
hemispherium wants to merge 2 commits into
mainfrom
0617-merge-two-binary-trees

Conversation

@hemispherium
Copy link
Copy Markdown
Owner

@hemispherium hemispherium self-assigned this Apr 14, 2026
root1->right = mergeTrees(root1->right, root2->right);
return root1;
}
};
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

まず、入力を壊すものであることは注意が必要で、コメントがあると嬉しいかなと思います。
root1の値を更新しているところです。

あとは、root1がないときはroot2を返しているところは、root2の一部を出力が含んでいるので、出来上がった木からもroot2からも、一部書き換えができてしまいます。

入力を壊さずに新しいノードを作っていくという方法もあります。この場合は、片方のノードがないと不便(valどうし足し算できない)なので、ダミーのノードを用意しておくというやり方もあります。

コメント集にいろいろ載っていると思います。

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.

コメントありがとうございます!
コメントを参考に、非破壊版のコードをalternative-solution.cppで追加してみました。

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