Swift solution - iterative, recursive


  • 0
    class Solution {
        func flatten(_ root: TreeNode?) {
            guard let root = root else { return }
            
            var stack = [TreeNode]()
            
            stack.append(root)
            while !stack.isEmpty {
                let node = stack.removeLast()
                if let right = node.right {
                    stack.append(right)
                }
                if let left = node.left {
                    stack.append(left)
                }
                if !stack.isEmpty {
                    node.right = stack.last
                }
                node.left = nil
            }
        }
        
        func flatten_rec(_ root: TreeNode?) {
            guard let root = root else { return }
            
            let left = root.left
            let right = root.right
            
            root.left = nil
            flatten_rec(left)
            flatten_rec(right)
            root.right = left
            
            var node = root
            while let nodeRight = node.right {
                node = nodeRight
            }
            node.right = right
        }
    }
    

Log in to reply
 

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