Home > AI > Data Structure > Tree > Binary Search Tree >

leetcode-226-Invert Binary Tree

Swift solution

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public var val: Int
 *     public var left: TreeNode?
 *     public var right: TreeNode?
 *     public init() { self.val = 0; self.left = nil; self.right = nil; }
 *     public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
 *     public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
 *         self.val = val
 *         self.left = left
 *         self.right = right
 *     }
 * }
 */
class Solution {
    func invertTree(_ root: TreeNode?) -> TreeNode? {
        // tree exits?
        
        guard let root = root else {
            return nil
        }

        let left: TreeNode? = invertTree(root.left)
        let right: TreeNode? = invertTree(root.right)

        root.left = right
        root.right = left
   
        return root
    }
}

Leave a Reply