Swift solution


  • 0
    class solution {
        func connect(_ root: TreeLinkNode?) {
            var head: TreeLinkNode? = nil
            var prev: TreeLinkNode? = nil
            var current: TreeLinkNode? = root
            
            while current != nil {
                while current != nil {
                    if current?.left != nil {
                        if prev != nil {
                            prev?.next = current?.left
                        } else {
                            head = current?.left
                        }
                        prev = current?.left
                    }
                    
                    if current?.right != nil {
                        if prev != nil {
                            prev?.next = current?.right
                        } else {
                            head = current?.right
                        }
                        prev = current?.right
                    }
                    
                    current = current?.next
                }
                
                current = head
                head = nil
                prev = nil
            }
        }
    }
    

Log in to reply
 

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