<div class="image-package"><img src="https://img.haomeiwen.com/i1648392/2abb91b8ef3485ef.jpg" contenteditable="false" img-data="{"format":"jpeg","size":406193,"height":900,"width":1600}" class="uploaded-img" style="min-height:200px;min-width:200px;" width="auto" height="auto"/>
</div><blockquote><p>给定两个二叉树,想象当你将它们中的一个覆盖到另一个上时,两个二叉树的一些节点便会重叠。
你需要将他们合并为一个新的二叉树。合并的规则是如果两个节点重叠,那么将他们的值相加作为节点合并后的新值,否则不为 NULL 的节点将直接作为新二叉树的节点。
示例 1:
输入:
Tree 1 Tree 2
1 2
/ \ / \
3 2 1 3
/ \ \
5 4 7
输出:
合并后的树:
3
/ <br/> 4 5
/ \ \
5 4 7
注意: 合并必须从两个树的根节点开始。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/merge-two-binary-trees
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。</p></blockquote><h1 id="it8ek">题解</h1><div class="image-package"><img src="https://img.haomeiwen.com/i1648392/8c0eb590c298d196.jpg" contenteditable="false" img-data="{"format":"jpeg","size":71119,"height":820,"width":1536}" class="uploaded-img" style="min-height:200px;min-width:200px;" width="auto" height="auto"/>
</div><h2 id="22m2o">Swift</h2><blockquote><p>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 let root1 = root1 else {
return root2
}
guard let root2 = root2 else {
return root1
}
let root = TreeNode(root1.val + root2.val)
root.left = mergeTrees(root1.left, root2.left)
root.right = mergeTrees(root1.right, root2.right)
return root
}
}
let a5 = TreeNode(5)
let a2 = TreeNode(2)
let a3 = TreeNode(3, a5, nil)
let a1 = TreeNode(1, a3, a2)
let b4 = TreeNode(4)
let b7 = TreeNode(7)
let b1 = TreeNode(1, nil, b4)
let b3 = TreeNode(3, nil, b7)
let b2 = TreeNode(2, b1, b3)
var result = Solution().mergeTrees(a1, b2)
func bfs(_ root: TreeNode?) {
guard root != nil else {
return
}
print(root?.val as Any)
bfs(root?.left)
bfs(root?.right)
}
bfs(result)
</p></blockquote><p>
</p><p>
</p><p>
</p><p>
</p><p>
</p><p>
</p>
网友评论