Grokking the Coding Interview: The Original Course
Vote

0% completed

​

Solution: Problem Challenge 1: Connect All Level Order Siblings

Problem Statement

Given a root of the binary tree, connect each node with its level order successor. The last node of each level should point to the first node of the next level.

Examples

Example 1

  • Input: root = [1, 2, 3, 4, 5, 6, 7]
  • Output: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> null
  • Explanation: The tree is traversed level by level using BFS. Each node is connected to its next node in level order traversal, including connections between levels. The last node (7) points to null.

.....

.....

.....

Like the course? Get enrolled and start learning!
M

mosharaf.hossain221

· 5 days ago

def connect(self, root):     if not root:       return root     levelStart = root     prev = root     while levelStart:       nextLevelStart = None       current = levelStart       while current:         for child in (current.left, current.right):           if not child:             continue                     if not prev:             nextLevelStart = child           else:             prev.next = child                     prev = child         current = current.next       levelStart = nextLevelStart     return root
A

Anthony DiFede

· 4 years ago

I don't believe you need a previous. Just set currentNode.next to the head of the Queue. On the very last iteration/node the queue will be empty so currentNode.next = null.

Image

Reading Progress

0%


Vote for new content