알고리즘/해결

LeetCode226. Invert Binary Tree

언클린 2020. 4. 14. 15:34
728x90

1. 문제(원본)

Invert a binary tree.

Example:

Input:

4 / \ 2 7 / \ / \ 1 3 6 9

Output:

4 / \ 7 2 / \ / \ 9 6 3 1

2. 문제

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 invertTree(_ root: TreeNode?) -> TreeNode? {

        guard root != nil else {

            return nil

        }

        let temp = root?.left

        root?.left = root?.right

        root?.right = temp

        invertTree(root?.left)

        invertTree(root?.right)

        return root

    }

}

4. 다른 유저의 답

#1

func invertTree(_ root: TreeNode?) -> TreeNode? {

    if root == nil { return root }

    let left = invertTree(root?.left)

    let right = invertTree(root?.right)

    root?.left = right

    root?.right = left

    return root

}

5. 마무리

나는 위치를 바꾸는 것이기 때문에 스왑 처리를 하였는데 다른 유저들의 답을 보면 더욱 간단히 해결한 것을 알 수 있었다.

728x90

'알고리즘 > 해결' 카테고리의 다른 글

LeetCode1431. Kids With the Greatest Number of Candies  (0) 2020.05.18
LeetCode821. Shortest Distance to a Character  (0) 2020.04.20
LeetCode412. Fizz Buzz  (0) 2020.04.12
LeetCode868. Binary Gap  (0) 2020.04.12
LeetCode283. Move Zeroes  (0) 2020.04.12