-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0116-populating-next-right-pointers-in-each-node.kt
62 lines (53 loc) · 1.67 KB
/
0116-populating-next-right-pointers-in-each-node.kt
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// Time complexity O(n) and space complexity O(1) with Follow-up constraints, without using recursion
class Solution {
fun connect(root: Node?): Node? {
var cur = root
var next = cur?.left
while (cur != null && next != null) {
cur?.left?.next = cur?.right
if (cur?.next != null)
cur?.right?.next = cur?.next?.left
cur = cur?.next
if (cur == null) {
cur = next
next = cur?.left
}
}
return root
}
}
// Time complexity O(n) and space complexity O(1) with Follow-up constraints using recursion
class Solution {
fun connect(root: Node?): Node? {
root?: return null
root.left?.let {
it.next = root.right
root.right?.let {
it.next = root.next?.left
}
connect(root.left)
connect(root.right)
}
return root
}
}
// Time complexity O(n) and space complexity O(logn)
class Solution {
fun connect(root: Node?): Node? {
with (LinkedList<Pair<Node?, Int>>()) {
addLast(root to 0)
while (isNotEmpty()) {
repeat (size) {
val (curNode, curLevel) = removeFirst()
peekFirst()?.let { (nextNode, nextLevel) ->
if (nextLevel == curLevel)
curNode?.next = nextNode
}
curNode?.left?.let { addLast(it to (curLevel + 1)) }
curNode?.right?.let { addLast(it to (curLevel + 1)) }
}
}
}
return root
}
}