[LeetCode] 617. Merge Two Binary Trees / Swift
[문제 보기]
You are given two binary trees root1 and root2.
Imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge the two trees into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of the new tree.
Return the merged tree.
Note: The merging process must start from the root nodes of both trees.
Example 1:

Input: root1 = [1,3,2,5], root2 = [2,1,3,null,4,null,7] Output: [3,4,5,5,4,null,7]
Example 2:
Input: root1 = [1], root2 = [1,2] Output: [2,2]
Constraints:
- The number of nodes in both trees is in the range [0, 2000].
- -104 <= Node.val <= 104
https://leetcode.com/problems/merge-two-binary-trees/
Merge Two Binary Trees - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
2개의 트리를 묶어서 수평탐색하면서 새로운 트리를 만드는 방법으로 해결했다.
이진트리 노드로 다루는법 더 연습해야겠다..
/**
* Definition for a binary tree node.
* public class TreeNode {
* public var val: Int
* public var left: TreeNode?
* public var right: TreeNode?
* public init() { self.val = 0; self.left = nil; self.right = nil; }
* public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
* public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
* self.val = val
* self.left = left
* self.right = right
* }
* }
*/
class Solution {
func mergeTrees(_ root1: TreeNode?, _ root2: TreeNode?) -> TreeNode? {
guard root1 != nil || root2 != nil else {
return nil
}
let ans = TreeNode()
var queue = [(ans, root1, root2)]
while !queue.isEmpty {
let node = queue.removeFirst()
node.0.val = (node.1?.val ?? 0) + (node.2?.val ?? 0)
if node.1?.left != nil || node.2?.left != nil {
node.0.left = TreeNode()
queue.append((node.0.left!, node.1?.left, node.2?.left))
}
if node.1?.right != nil || node.2?.right != nil {
node.0.right = TreeNode()
queue.append((node.0.right!, node.1?.right, node.2?.right))
}
}
// func search(_ t: TreeNode?) {
// if t == nil { return }
// print(t?.val)
// search(t?.left)
// search(t?.right)
// }
// search(ans)
return ans
}
}