难点是对递归的理解,建议自己在纸上画一画,模拟一下程序的运行过程输出,有助于理解递归。
/**
* Definition for a binary tree node.
* public class TreeNode {
* public var val: Int
* public var left: TreeNode?
* public var right: TreeNode?
* public init(_ val: Int) {
* self.val = val
* self.left = nil
* self.right = nil
* }
* }
*/
class Solution {
func invertTree(_ root: TreeNode?) -> TreeNode? {
if root == nil {
return nil
}
root?.left = invertTree(root?.left)
root?.right = invertTree(root?.right)
var tmp = root?.left
root?.left = root?.right
root?.right = tmp
return root
}
}