LeetCode430. 扁平化多级双向链表
1. 问题描述


2. 思路
3. 代码
/**
* Definition for a Node.
* type Node struct {
* Val int
* Prev *Node
* Next *Node
* Child *Node
* }
*/
func flatten(root *Node) *Node {
dfs(root)
return root
}
func dfs(node *Node) *Node {
var last *Node
cur := node
for cur != nil {
next := cur.Next
// 处理子节点
if cur.Child != nil {
childLast := dfs(cur.Child)
next = cur.Next
// 将node与child连起来
cur.Next = cur.Child
cur.Child.Prev = cur
// 将last与next连起来
if next != nil {
childLast.Next = next
next.Prev = childLast
}
// 将child置为空
cur.Child = nil
last = childLast
} else {
last = cur
}
cur = next
}
return last
}
这篇博客介绍了如何解决LeetCode第430题,即扁平化多级双向链表的问题。通过深度优先搜索(DFS)策略,将一个多级的双向链表转化为单级链表。代码中定义了Node结构体,并展示了如何遍历并连接各个节点,确保所有子节点被正确地连接到主链表中。
540

被折叠的 条评论
为什么被折叠?



