Skip to content

Commit 9dd9c1d

Browse files
committed
Added constant space solutions for populating next right pointers
1 parent 327632a commit 9dd9c1d

2 files changed

+33
-2
lines changed

Populating Next Right Pointers in Each Node II.py

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,4 +13,21 @@ def connect(self, root):
1313
if current[i].right is not None:
1414
next.append(current[i].right)
1515
current = next
16-
return root
16+
return root
17+
18+
#### constant space solution
19+
def connect_2(self, root):
20+
if not root:
21+
return
22+
nexthead = root
23+
while nexthead:
24+
c, nexthead, prevs = nexthead, None, None
25+
while c:
26+
for x in [c.left, c.right]:
27+
if x:
28+
if not nexthead:
29+
nexthead, prevs = x, x
30+
else:
31+
prevs.next, prevs = x, x
32+
c = c.next
33+
Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
class Solution:
2+
23
def connect(self, root):
34
if root is None:
45
return
@@ -7,4 +8,17 @@ def connect(self, root):
78
if root.right and root.next:
89
root.right.next = root.next.left
910
self.connect(root.left)
10-
self.connect(root.right)
11+
self.connect(root.right)
12+
13+
# constant space solution
14+
def connect_2(self, root):
15+
head = root
16+
while head:
17+
current = head
18+
while current:
19+
if current.left:
20+
current.left.next = current.right
21+
if current.next:
22+
current.right.next = current.next.left
23+
current = current.next
24+
head = head.left

0 commit comments

Comments
 (0)