Skip to content

Commit 631a14b

Browse files
committed
problem: 0116 populating next right pointers in each node
1 parent 5888cdb commit 631a14b

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
# 0116. Populating Next Right Pointers in Each Node
2+
3+
* Difficulty: medium
4+
* Link: https://leetcode.com/problems/populating-next-right-pointers-in-each-node/
5+
* Topics: DFS-BFS
6+
7+
# Clarification
8+
9+
1. Check the inputs and outputs
10+
- INPUT:
11+
- OUTPUT:
12+
13+
# Naive Solution
14+
15+
### Thought Process
16+
17+
1. BFS
18+
- Implement
19+
20+
```python
21+
"""
22+
# Definition for a Node.
23+
class Node:
24+
def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
25+
self.val = val
26+
self.left = left
27+
self.right = right
28+
self.next = next
29+
"""
30+
31+
class Solution:
32+
def connect(self, root: 'Optional[Node]') -> 'Optional[Node]':
33+
if not root:
34+
return root
35+
36+
q = collections.deque()
37+
q.append(root)
38+
while q:
39+
lenQ = len(q)
40+
for i in range(lenQ):
41+
current = q.popleft()
42+
if current.left:
43+
q.append(current.left)
44+
if current.right:
45+
q.append(current.right)
46+
if i == 0:
47+
prev = current
48+
else:
49+
prev.next = current
50+
prev = current
51+
prev.next = None
52+
return root
53+
```
54+
55+
56+
### Complexity
57+
58+
- Time complexity: O(N)
59+
- Space complexity: O(N)

0 commit comments

Comments
 (0)