cubegao

Swift.二叉树的镜像

2015-07-10

题目描述:操作给定的二叉树,将其变换为源二叉树的镜像。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import Foundation

class For19Solution {
func mirrorTreeNode(_ root: TreeNode?) -> TreeNode? {

if root == nil || (root?.left == nil && root?.right == nil) {
return nil
}

let temp = root?.left
root?.left = root?.right
root?.right = temp

if root?.left != nil {
mirrorTreeNode(root?.left)
}

if root?.right != nil {
mirrorTreeNode(root?.right)
}

return root
}
}

算法思想:递归,利用栈结构。交换左右孩子,然后递归访问左右孩子。

github地址:https://github.com/cubegao/LeetCode

Tags: 算法

扫描二维码,分享此文章