美文网首页
剑指 Offer II 028. 展平多级双向链表

剑指 Offer II 028. 展平多级双向链表

作者: 邦_ | 来源:发表于2022-04-22 10:36 被阅读0次
    var endNode:Node?
        
        func flatten(_ head: Node?) -> Node? {
        
            if head == nil {
                return head
            }
            dfs(head)
            return head
        
        }
        
        func dfs(_ head:Node?){
            var tempHead = head
            var next : Node? = nil
            while tempHead != nil {
                //保存递归结束节点
                if(tempHead?.next == nil){
                    endNode = tempHead
                }
                next = tempHead?.next
                if(tempHead?.child != nil){
                    //当前节点和子节点相连
                    let child = tempHead?.child
                    tempHead?.next = child
                    child?.prev = tempHead
                    //将当前节点的子节点置空
                    tempHead?.child = nil
                    dfs(child)
                    // 递归结束尾节点与下一节点相连
                    if endNode != nil && next != nil {
                        endNode?.next = next
                        next?.prev = endNode
                    }
                }
                
                tempHead = next
       
            }
        }
    
    
    
    
    
    
    
    
    
    
    
    
    

    相关文章

      网友评论

          本文标题:剑指 Offer II 028. 展平多级双向链表

          本文链接:https://www.haomeiwen.com/subject/kefdertx.html