-
[LeetCode] 226. Invert Binary Tree / Swift프로그래밍/코딩테스트 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/
이진트리의 모든 자식들의 위치를 서로 바꾸는 문제였다.
/** * 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 } }
반응형'프로그래밍 > 코딩테스트' 카테고리의 다른 글
[LeetCode] 283. Move Zeroes / Swift (0) 2021.06.26 [LeetCode] 234. Palindrome Linked List / Swift (0) 2021.06.26 [LeetCode] 206. Reverse Linked List / Swift (0) 2021.06.25 [LeetCode] 141. Linked List Cycle / Swift (0) 2021.06.25 [LeetCode] 136. Single Number / Swift (0) 2021.06.24