LeetCode反转二叉树Swift 面试

给你一棵二叉树的根节点 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
    }
}

 

转自:https://leetcode-cn.com/problems/invert-binary-tree/

posted @ 2022-03-21 11:55  黄增松  阅读(29)  评论(0编辑  收藏  举报