1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
| # Definition for a Node.
# class Node
# attr_accessor :val, :left, :right, :next
# def initialize(val)
# @val = val
# @left, @right, @next = nil, nil, nil
# end
# end
def process_child(child, previous, head)
if child
if previous
previous.next = child
else
head = child
end
previous = child
end
[previous, head]
end
# @param {Node} root
# @return {Node}
def connect(root)
if root.nil?
return
end
head = root
while head
previous, current = nil, head
head = nil
while current
previous, head = process_child(current.left, previous, head)
previous, head = process_child(current.right, previous, head)
current = current.next
end
end
root
end
|