Skip to content

Commit 7e5afc8

Browse files
committed
Time: 43 ms (59.64%) | Memory: 17.5 MB (95.38%) - LeetSync
1 parent d7de1ff commit 7e5afc8

File tree

1 file changed

+25
-12
lines changed

1 file changed

+25
-12
lines changed
Lines changed: 25 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,27 @@
1-
class Solution:
2-
def connect(self, root: Optional['Node']) -> Optional['Node']:
1+
# Definition for a Node.
2+
class Node:
3+
def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
4+
self.val = val
5+
self.left = left
6+
self.right = right
7+
self.next = next
8+
9+
class Solution:
10+
def connect(self, root: Optional[Node]) -> Optional[Node]:
11+
# Define a depth-first search (DFS) function to connect nodes on the same level
312
def dfs(node):
13+
# Base case: if the node is None, return None
414
if not node:
515
return None
6-
16+
17+
# Store the next node on the same level
718
next_node = node.next
8-
while next_node and next_node.next:
9-
if next_node.left or next_node.right:
10-
break
11-
else:
12-
next_node = next_node.next
13-
14-
19+
20+
# Iterate to find the next non-null node on the same level
21+
while next_node and not (next_node.left or next_node.right):
22+
next_node = next_node.next
23+
24+
# Connect the left and right child nodes
1525
if node.left and node.right:
1626
node.left.next = node.right
1727
if next_node:
@@ -20,9 +30,12 @@ def dfs(node):
2030
node.left.next = next_node.left or next_node.right
2131
elif node.right and next_node:
2232
node.right.next = next_node.left or next_node.right
33+
34+
# Recursively call the DFS function on the right and left child nodes
2335
dfs(node.right)
2436
dfs(node.left)
37+
2538
return node
2639

27-
28-
return dfs(root)
40+
# Call the DFS function on the root node and return the root
41+
return dfs(root)

0 commit comments

Comments
 (0)