Skip to content

Conversation

@kazukiii
Copy link
Owner

@kazukiii kazukiii commented Jul 9, 2024

問題へのリンク
https://leetcode.com/problems/merge-two-binary-trees/description/

次に解く問題
108. Convert Sorted Array to Binary Search Tree

README.mdへ頭の中の言語化と記録をしています。

class Solution:
def mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]:
if not root1 and not root2: return None
if not root1: return TreeNode(root2.val)

Choose a reason for hiding this comment

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

なんか実装できてない気がします。LeetCodeで用意されているテストケースは全部通るみたいなのですが。roo2しかないときにroot2の頂点のノードしかコピーしてなくてその子どもたちがコピーできていなさそうです。

たとえば、root1 = [1,3,2,5], root2 = []のケースとかでfailすると思います。

Copy link
Owner Author

Choose a reason for hiding this comment

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

子どもごと返さないといけないですね。ご指摘ありがとうございます。

- こちらもめちゃくちゃシンプル
- https://github.com/fhiyo/leetcode/pull/25
- 行きがけで書くにしてももう少し条件を整理できそう
- 帰りがけDFSで実装してみる
Copy link

Choose a reason for hiding this comment

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

https://discord.com/channels/1084280443945353267/1201211204547383386/1218151037697917028
帰りの処理が書き込みだけならば、子供に書き込み先のポインタを渡して書き込んでもらう手があります。

Copy link
Owner Author

Choose a reason for hiding this comment

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

ありがとうございます。確認します。

merged_root.right = deepcopy(root1.right)
continue

if root1.left or root2.left:

Choose a reason for hiding this comment

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

ちょっとif root1.left or root2.left:とif root1.left: left_sum += root1.left.valがifの処理が重複していて長いかなという気がしたので

left_sum = 0
if root1.left:
    left_sum += root1.left.val
if root2.left:
    left_sum += root2.left.val
merged_root.left = TreeNode(left_sum)

とか書き換えてみるとどうでしょうか

Copy link
Owner Author

Choose a reason for hiding this comment

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

んー、if root1.left or root2.left:の条件を外すと両方Noneの場合でも値が0のノードを追加することになってしまうんですよね。。とはいえleftとrightに対して全く同じ処理をしているので関数化はした方が良さそうです。

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.

5 participants