117. Populating Next Right Pointers in Each Node II
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL
.
Initially, all next pointers are set to NULL
.
def connect(root: 'Node'):
cur = root, left_most = None prev = None
while cur:
if cur.left:
if prev:
prev.next = cur.left
else:
left_most = cur.left
prev = cur.left
if cur.right:
if prev:
prev.next = cur.right
else:
left_most = cur.right
prev = cur.right
if cur.next:
cur = cur.next
else:
cur = left_most
prev = None
left_most = None
return root
def connect(root: 'Node'):
if not root:
return root
q = deque()
q.append((root,0))
levels = {}
while q:
cur, level = q.popleft()
if level not in levels:
levels[level] = []
levels[level].append(cur)
if cur.left:
q.append((cur.left, level+1))
if cur.right:
q.append((cur.right, level+1))
for level in levels:
for i in range(len(levels[level])-1):
levels[level][i].next = levels[level][i+1]
return root
Comments
Post a Comment