Skip to content

617. Merge Two Binary Trees#23

Open
hiroki-horiguchi-dev wants to merge 1 commit into
mainfrom
tree-bst-617
Open

617. Merge Two Binary Trees#23
hiroki-horiguchi-dev wants to merge 1 commit into
mainfrom
tree-bst-617

Conversation

@hiroki-horiguchi-dev
Copy link
Copy Markdown
Owner

617. Merge Two Binary Treesを解きました。

@hiroki-horiguchi-dev hiroki-horiguchi-dev self-assigned this Jun 2, 2026
@hiroki-horiguchi-dev hiroki-horiguchi-dev changed the title solve 617 617. Merge Two Binary Trees Jun 2, 2026
Comment thread tree-bst/617.md
- 時間計算量, 空間計算量: O(N) root1, root2 の大きい方に依存する
- スタックオーバーフローが発生する可能性を考え始めないといけない
- Queue
- root1, root2 で和をとるべき相対位置はQueueを使うと管理しやすいなということで、パッと思いついたが、じゃあノードの張り替えをどうするか?で完全に詰まってしまった
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

せっかくなので再度トライしてみて下さい。

入力の木を変更しないためには、新しい木を作ればよいですね。
例えば次のように場合分けする良いと思います。

あるノードを作るときに、
1)両方の木にノードがある場合:値を足し合わせたノードを作る
(これは、載せていただいたコードを見る限り、すでにできると思います。)
2)片方の木にしかノードがない場合:存在しない側を 0 とみなし、(存在する側の値+0)を値に持つノードを作る
3)両方とも null の場合: 何もしない

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.

ですね、再度トライします。
新しい木を作る時に、新しい木の先頭をどこに持っておくかが、パッと思いつかなくて再帰でいいやとなっています。

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

それでしたら、以下のPRを参考にしてみてください。
https://github.com/seal-azarashi/leetcode/pull/22/changes

また、コードだけでなくPRの中のコメントについても考えてみてもいいかもしれません。

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