File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change 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+
You can’t perform that action at this time.
0 commit comments