Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- class Node:
- def __init__(self, val):
- self.right = None
- self.data = val
- self.left = None
- self.nextRight = None
- '''
- '''
- Logic: Used BFS traversal level by level.Stored nodes in deque and connected each node's nextRight to its adjacent right node in the same level.
- TC: O(N), Every node is visited once.
- '''
- from collections import deque
- class Solution:
- def connect(self, root):
- if not root:
- return
- q = deque()
- q.append(root)
- while q:
- k = len(q)
- for i in range(k):
- temp = q.popleft()
- # last node of current level
- if i == k - 1:
- temp.nextRight = None
- else:
- temp.nextRight = q[0]
- if temp.left:
- q.append(temp.left)
- if temp.right:
- q.append(temp.right)
Advertisement
Add Comment
Please, Sign In to add comment