Skip to content

Commit 54a7502

Browse files
committed
Add 116, 117
1 parent 2e364ae commit 54a7502

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

2024/meta/prep.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -784,3 +784,40 @@ def removeDuplicates(self, s: str) -> str:
784784

785785

786786
return ''.join(stack)
787+
788+
789+
############# 116. Populating Next Right Pointers in Each Node II #############
790+
791+
class Solution:
792+
def connect(self, root: 'Optional[Node]') -> 'Optional[Node]':
793+
def traverse(left, right):
794+
if not left or not right:
795+
return
796+
left.next = right
797+
traverse(left.left, left.right)
798+
traverse(left.right, right.left)
799+
traverse(right.left, right.right)
800+
if root:
801+
traverse(root.left, root.right)
802+
return root
803+
804+
############# 117. Populating Next Right Pointers in Each Node II #############
805+
class Solution:
806+
def connect(self, root: 'Optional[Node]') -> 'Optional[Node]':
807+
808+
if not root:
809+
return None
810+
queue = deque([root])
811+
while queue:
812+
sz = len(queue)
813+
for i in range(sz):
814+
node = queue.popleft()
815+
if node.left:
816+
queue.append(node.left)
817+
if node.right:
818+
queue.append(node.right)
819+
820+
if i < sz-1: # don't set the next pointer of last node of the same level,
821+
# otherwise it will point to first node of next level
822+
node.next = queue[0]
823+
return root

0 commit comments

Comments
 (0)