Home > AI > Data Structure > Tree >

leetcode-617-Merge Two Binary Trees

swift solution:

/**
 * 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(_ t1: TreeNode?, _ t2: TreeNode?) -> TreeNode? {
        //none of the tree is null
        guard let t1 = t1 else { return t2 }
        guard let t2 = t2 else { return t1 }
        
        // merge root
        let root: TreeNode = TreeNode(t1.val + t2.val)
        
        // merge branch
        let left: TreeNode? = mergeTrees(t1.left, t2.left)
        let right: TreeNode? = mergeTrees(t1.right, t2.right)
        root.left = left 
        root.right = right
        
        return root
    }
}

Leave a Reply