/**
* Definition for a Node.
* type Node struct {
* Val int
* Left *Node
* Right *Node
* Next *Node
* }
*/funcconnect(root*Node)*Node{ifnil==root{returnroot}varqueue[]*Nodequeue=append(queue,root)forlen(queue)>0{cnt:=len(queue)varprev*Nodeforcnt>0{cur:=queue[0]queue=queue[1:]ifprev!=nil{prev.Next=cur}prev=curifcur.Left!=nil{queue=append(queue,cur.Left)}ifcur.Right!=nil{queue=append(queue,cur.Right)}cnt--}}returnroot}
/**
* Definition for a Node.
* type Node struct {
* Val int
* Left *Node
* Right *Node
* Next *Node
* }
*/funcconnect(root*Node)*Node{prevNodes:=make(map[int]*Node)vardfsfunc(root*Node,depthint)dfs=func(root*Node,depthint){ifroot==nil{return}ifprev,has:=prevNodes[depth];has{prev.Next=root}prevNodes[depth]=rootdfs(root.Left,depth+1)dfs(root.Right,depth+1)}dfs(root,0)returnroot}
/**
* Definition for a Node.
* type Node struct {
* Val int
* Left *Node
* Right *Node
* Next *Node
* }
*/funcconnect(root*Node)*Node{dummy:=&Node{}up,down:=root,dummyforup!=nil&&up.Left!=nil{forup!=nil{down.Next=up.Leftdown=down.Nextdown.Next=up.Rightdown=down.Nextup=up.Next}up=dummy.Nextdown=dummy}returnroot}