Created
July 9, 2020 18:11
-
-
Save alldroll/e6cb3df706757f6e517ac21d61401b76 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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