imashutosh51

Connect Nodes at same level

Jul 23rd, 2022 (edited)
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.99 KB | None | 0 0
  1. '''
  2. class Node:
  3.    def __init__(self, val):
  4.        self.right = None
  5.        self.data = val
  6.        self.left = None
  7.        self.nextRight = None
  8. '''
  9. '''      
  10. 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.
  11. TC: O(N), Every node is visited once.
  12. '''
  13.  
  14. from collections import deque
  15. class Solution:
  16.     def connect(self, root):
  17.         if not root:
  18.             return
  19.         q = deque()
  20.         q.append(root)
  21.         while q:
  22.             k = len(q)
  23.             for i in range(k):
  24.                 temp = q.popleft()
  25.                
  26.                 # last node of current level
  27.                 if i == k - 1:
  28.                     temp.nextRight = None
  29.                 else:
  30.                     temp.nextRight = q[0]
  31.                
  32.                 if temp.left:
  33.                     q.append(temp.left)
  34.                 if temp.right:
  35.                     q.append(temp.right)
Advertisement
Add Comment
Please, Sign In to add comment