Skip to content

Commit 2252fd2

Browse files
committed
problem: 0117 populating next right pointers in each node II
1 parent 631a14b commit 2252fd2

File tree

1 file changed

+61
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)