-
Notifications
You must be signed in to change notification settings - Fork 0
617. Merge Two Binary Trees #24
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
| 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) |
There was a problem hiding this comment.
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すると思います。
There was a problem hiding this comment.
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で実装してみる |
There was a problem hiding this comment.
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
帰りの処理が書き込みだけならば、子供に書き込み先のポインタを渡して書き込んでもらう手があります。
There was a problem hiding this comment.
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: |
There was a problem hiding this comment.
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)とか書き換えてみるとどうでしょうか
There was a problem hiding this comment.
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に対して全く同じ処理をしているので関数化はした方が良さそうです。
問題へのリンク
https://leetcode.com/problems/merge-two-binary-trees/description/
次に解く問題
108. Convert Sorted Array to Binary Search Tree
README.mdへ頭の中の言語化と記録をしています。