Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save alldroll/e6cb3df706757f6e517ac21d61401b76 to your computer and use it in GitHub Desktop.
Save alldroll/e6cb3df706757f6e517ac21d61401b76 to your computer and use it in GitHub Desktop.
/**
* Definition for a Node.
* type Node struct {
* Val int
* Left *Node
* Right *Node
* Next *Node
* }
*/
type LevelNode struct {
node *Node
level int
}
func connect(root *Node) *Node {
if root == nil {
return nil
}
queue := []*LevelNode{{
node: root,
level: 0,
}}
var prev *LevelNode
for len(queue) > 0 {
item := queue[0]
queue = queue[1:]
if item.node.Left != nil {
queue = append(queue, &LevelNode{
node: item.node.Left,
level: item.level + 1,
})
}
if item.node.Right != nil {
queue = append(queue, &LevelNode{
node: item.node.Right,
level: item.level + 1,
})
}
if prev != nil && prev.level == item.level {
prev.node.Next = item.node
}
prev = item
}
return root
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment