226. 翻转二叉树 - 简单
xxxixxxx

226. 翻转二叉树

226. 翻转二叉树

迭代解法

  • 时间复杂度
    O(n) n 为节点个数,每个节点访问一次
  • 空间复杂度
    O(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// 从根节点开始反转的
func invertTree2(_ root: TreeNode?) -> TreeNode? {
guard let root = root else { return nil }

var treeRoot = root
let ansRoot = root
var list: [TreeNode] = [treeRoot]
while !list.isEmpty {
treeRoot = list.popLast()!
let temp = treeRoot.right
treeRoot.right = treeRoot.left
treeRoot.left = temp
if treeRoot.left != nil {
list.append(treeRoot.left!)
}
if treeRoot.right != nil {
list.append(treeRoot.right!)
}
}

return ansRoot
}

递归解法

  • 时间复杂度
    O(n) n 为节点个数,每个节点访问一次
  • 空间复杂度
    O(n)
1
2
3
4
5
6
7
8
9
// 从叶子节点开始反转的
func invertTree(_ root: TreeNode?) -> TreeNode? {
guard let root = root else { return nil }
let left = invertTree(root.left)
let right = invertTree(root.right)
root.left = right
root.right = left
return root
}
  • Post title:226. 翻转二叉树 - 简单
  • Post author:xxxixxxx
  • Create time:2021-02-24 15:47:00
  • Post link:https://xxxixxx.github.io/2021/02/24/2000-017-226. 翻转二叉树/
  • Copyright Notice:All articles in this blog are licensed under BY-NC-SA unless stating additionally.
 Comments