알고리즘/해결

LeetCode617. Merge Two Binary Trees

언클린 2020. 3. 18. 20:32
728x90

1. 문제(원본)

Given two binary trees and 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 them 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 new tree.

Note: The merging process must start from the root nodes of both trees.

2. 문제

두 개의 트리의 합을 구하라

public class TreeNode {

    public var val: Int

    public var left: TreeNode?

    public var right: TreeNode?

    public init(_ val: Int) {

        self.val = val

        self.left = nil

        self.right = nil

    }

 }

3. 나의 답

class Solution {

    func mergeTrees(_ t1: TreeNode?, _ t2: TreeNode?) -> TreeNode? {

        guard t1 != nil || t2 != nil else {

            return nil

        }

        guard t1 != nil else {

            return t2

        }

        guard t2 != nil else {

            return t1

        }

 

        t1?.val = ((t1?.val ?? 0) + (t2?.val ?? 0))

        t1?.left = mergeTrees(t1?.left, t2?.left)

        t1?.right = mergeTrees(t1?.right, t2?.right)

 

        return t1

    }

}

4. 다른 유저의 답

#1

func mergeTrees(_ t1: TreeNode?, _ t2: TreeNode?) -> TreeNode? {

    if t1 == nil, t2 == nil { return nil }

    let root = TreeNode((t1?.val ?? 0) + (t2?.val ?? 0))

    root.left = mergeTrees(t1?.left, t2?.left)

    root.right = mergeTrees(t1?.right, t2?.right)

    return root

}

5. 마무리

트리...이번 문제가 풀리기 전까지는 생각을 가장 오래했던 것 같다. 재귀함수를 생각 못하고 함수내에서 처리할 생각만 하고 있었다.

해법을 깨달았을 때는 술술 풀렸던 문제였다. 하나의 경험이 쌓인 것 같다.

 

728x90