给你一棵二叉树的根节点 root
,翻转这棵二叉树,并返回其根节点。
示例 1:
示例 2:
/** * 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? { guard let root = root else { return nil } // 前序遍历--begin let temp = root.left root.left = root.right root.right = temp self.invertTree(root.left) self.invertTree(root.right) return root } }