Swift solution - Recursive, Stack, Queue


  • 0
    class Solution {
        func invertTree(_ root: TreeNode?) -> TreeNode? {
            guard let root = root else {
                return nil
            }
            
            let leftNode = root.left
            let rightNode = root.right
            
            root.left = invertTree(rightNode)
            root.right = invertTree(leftNode)
            
            return root
        }
        
        func invertTree_Stack(_ root: TreeNode?) -> TreeNode? {
            guard let root = root else {
                return nil
            }
            
            var stack = [TreeNode]()
            
            stack.append(root)
            while !stack.isEmpty {
                let node = stack.removeLast()
                swap(&node.left, &node.right)
                if let leftNode = node.left {
                    stack.append(leftNode)
                }
                if let rightNode = node.right {
                    stack.append(rightNode)
                }
            }
            
            return root
        }
        
        func invertTree_Queue(_ root: TreeNode?) -> TreeNode? {
            guard let root = root else {
                return nil
            }
            
            var queue = [TreeNode]()
            
            queue.append(root)
            while !queue.isEmpty {
                let node = queue.removeFirst()
                swap(&node.left, &node.right)
                if let leftNode = node.left {
                    queue.append(leftNode)
                }
                if let rightNode = node.right {
                    queue.append(rightNode)
                }
            }
            
            return root
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.