프로그래밍/코딩테스트

[LeetCode] 226. Invert Binary Tree / Swift

turu 2021. 6. 26. 00:13

[문제 보기]

더보기

Given the root of a binary tree, invert the tree, and return its root.

 

Example 1:

Input: root = [4,2,7,1,3,6,9] Output: [4,7,2,9,6,3,1]

Example 2:

Input: root = [2,1,3] Output: [2,3,1]

Example 3:

Input: root = [] Output: []

 

Constraints:

  • The number of nodes in the tree is in the range [0, 100].
  • -100 <= Node.val <= 100

 

https://leetcode.com/problems/invert-binary-tree/

 

Invert Binary Tree - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 


이진트리의 모든 자식들의 위치를 서로 바꾸는 문제였다.

 

/**
 * 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 invertTree(_ root: TreeNode?) -> TreeNode? {
        var queue = [root]
        
        while !queue.isEmpty {
            let first = queue.removeFirst()
            if first == nil {
                continue
            }
            // left, right 두개의 위치를 바꾼다
            let temp = first?.left
            first?.left = first?.right
            first?.right = temp
            queue.append(first?.left)
            queue.append(first?.right)
        }
        
        return root
    }
}
반응형