-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0117-populating-next-right-pointers-in-each-node-ii.py
More file actions
49 lines (37 loc) · 1.17 KB
/
0117-populating-next-right-pointers-in-each-node-ii.py
File metadata and controls
49 lines (37 loc) · 1.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# time complexity: O(n)
# space complexity: O(1)
from typing import Optional
class Node:
def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
self.val = val
self.left = left
self.right = right
self.next = next
class Solution:
def processChild(self, childNode, prev, leftmost):
if childNode:
if prev:
prev.next = childNode
else:
leftmost = childNode
prev = childNode
return prev, leftmost
def connect(self, root: Optional["Node"]) -> Optional["Node"]:
if not root:
return root
leftmost = root
while leftmost:
prev, curr = None, leftmost
leftmost = None
while curr:
prev, leftmost = self.processChild(curr.left, prev, leftmost)
prev, leftmost = self.processChild(curr.right, prev, leftmost)
curr = curr.next
return root
root = Node(1)
root.left = Node(2)
root.left.left = Node(4)
root.left.right = Node(5)
root.right = Node(3)
root.right.right = Node(7)
print(Solution().connect(root))