Skip to content

Commit e0af0f7

Browse files
authored
Create 0116-populating-next-right-pointers-in-each-node.kt
1 parent e2f2ecb commit e0af0f7

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
// Time complexity O(n) and space complexity O(1) with Follow-up constraints, without using recursion
2+
class Solution {
3+
fun connect(root: Node?): Node? {
4+
var cur = root
5+
var next = cur?.left
6+
7+
while (cur != null && next != null) {
8+
cur?.left?.next = cur?.right
9+
if (cur?.next != null)
10+
cur?.right?.next = cur?.next?.left
11+
12+
cur = cur?.next
13+
if (cur == null) {
14+
cur = next
15+
next = cur?.left
16+
}
17+
}
18+
19+
return root
20+
}
21+
}
22+
23+
// Time complexity O(n) and space complexity O(1) with Follow-up constraints using recursion
24+
class Solution {
25+
fun connect(root: Node?): Node? {
26+
root?: return null
27+
28+
root.left?.let {
29+
it.next = root.right
30+
root.right?.let {
31+
it.next = root.next?.left
32+
}
33+
connect(root.left)
34+
connect(root.right)
35+
}
36+
37+
return root
38+
}
39+
}
40+
41+
// Time complexity O(n) and space complexity O(logn)
42+
class Solution {
43+
fun connect(root: Node?): Node? {
44+
with (LinkedList<Pair<Node?, Int>>()) {
45+
addLast(root to 0)
46+
47+
while (isNotEmpty()) {
48+
repeat (size) {
49+
val (curNode, curLevel) = removeFirst()
50+
peekFirst()?.let { (nextNode, nextLevel) ->
51+
if (nextLevel == curLevel)
52+
curNode?.next = nextNode
53+
}
54+
curNode?.left?.let { addLast(it to (curLevel + 1)) }
55+
curNode?.right?.let { addLast(it to (curLevel + 1)) }
56+
}
57+
}
58+
}
59+
60+
return root
61+
}
62+
}

0 commit comments

Comments
 (0)