-
[LeetCode] 617. Merge Two Binary Trees / Swift프로그래밍/코딩테스트 2021. 6. 21. 00:47
[문제 보기]
더보기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/
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 } }
반응형'프로그래밍 > 코딩테스트' 카테고리의 다른 글
[Contest 246] 1904. The Number of ... / Swift (0) 2021.06.21 [Contest 246] 1903. Largest Odd Number in String / Swift (0) 2021.06.21 [LeetCode] 21. Merge Two Sorted Lists / Swift (0) 2021.06.20 [1926번] 그림 / Swift (0) 2021.06.20 [2020 카카오 인턴십] 경주로 건설 / Swift (0) 2021.06.17