Skip to content

Commit

Permalink
naive solution for "117. Populating Next Right Pointers in Each Node II"
Browse files Browse the repository at this point in the history
  • Loading branch information
lancelote committed Nov 11, 2024
1 parent 525baa3 commit ad15b28
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
38 changes: 38 additions & 0 deletions src/populating_next_right_pointers_in_each_node_ii.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
from __future__ import annotations

from collections import deque


class Node:
def __init__(
self,
val: int = 0,
left: Node | None = None,
right: Node | None = None,
next: Node | None = None,
):
self.val = val
self.left = left
self.right = right
self.next = next


class Solution:
def connect(self, root: Node | None) -> Node | None:
if not root:
return None

queue: deque[Node] = deque()
queue.append(root)

while queue:
for i in range(len(queue) - 1):
queue[i].next = queue[i + 1]
for _ in range(len(queue)):
node = queue.popleft()
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)

return root
21 changes: 21 additions & 0 deletions tests/test_populating_next_right_pointers_in_each_node_ii.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
from src.populating_next_right_pointers_in_each_node_ii import Node
from src.populating_next_right_pointers_in_each_node_ii import Solution


def test_example():
n7 = Node(7)
n3 = Node(3, right=n7)
n4 = Node(4)
n5 = Node(5)
n2 = Node(2, left=n4, right=n5)
n1 = Node(1, left=n2, right=n3)

Solution().connect(n1)

assert n1.next is None
assert n2.next is n3 and n3.next is None
assert n4.next is n5 and n5.next is n7 and n7.next is None


def test_empty():
assert Solution().connect(None) is None

0 comments on commit ad15b28

Please sign in to comment.