Skip to content

Commit 9b2ab2d

Browse files
committed
solve problem
1 parent 7ed9339 commit 9b2ab2d

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
public class TreeNode {
2+
public var val: Int
3+
public var left: TreeNode?
4+
public var right: TreeNode?
5+
public init() { self.val = 0; self.left = nil; self.right = nil; }
6+
public init( val: Int) { self.val = val; self.left = nil; self.right = nil; }
7+
public init( val: Int, * left: TreeNode?, * right: TreeNode?) {
8+
self.val = val
9+
self.left = left
10+
self.right = right
11+
}
12+
}
13+
14+
class Solution {
15+
// Time O(n)
16+
// Space O(n)
17+
func invertTree(_ root: TreeNode?) -> TreeNode? {
18+
guard let root = root else {
19+
return nil
20+
}
21+
22+
var queue: [TreeNode] = [root]
23+
24+
while queue.isEmpty == false {
25+
let current = queue.removeFirst()
26+
27+
if let left = current.left {
28+
queue.append(left)
29+
}
30+
31+
if let right = current.right {
32+
queue.append(right)
33+
}
34+
35+
(current.left, current.right) = (current.right, current.left)
36+
}
37+
38+
return root
39+
}
40+
}
41+

0 commit comments

Comments
 (0)