VOOZH about

URL: https://www.geeksforgeeks.org/dsa/connect-nodes-at-same-level/

⇱ Connect nodes at same level - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Connect nodes at same level

Last Updated : 1 Apr, 2026

Given a binary tree, connect the nodes that are at the same level. Given an addition nextRight pointer for the same. Initially, all the next right pointers point to garbage values, set these pointers to the point next right for each node.

Examples:

Input:

👁 Connect-Nodes-at-same-Level-2-

Output:

👁 Connect-Nodes-at-same-Level-

Explanation: The above tree represents the nextRight pointer connected the nodes that are at the same level.

Using Level Order Traversal - O(n) Time and O(n) Space

The idea is to use line by line level order traversal, we mainly count nodes at next level using queue size. As nodes are processed, each node's nextRight pointer is set to the next node in the queue.


Output
Next Right of 8 is 2
Next Right of 3 is 4

[Expected Approach] Using Already Set Next Rights - O(n) Time and O(1) Space 

  • We traverse the tree level by level using the already established nextRight pointers.
  • For each level, we iterate through all nodes using a loop and set nextRight of the next level.
  • To set next right of children of a node, for left child, we first check for the right child. And then traverse to nextRight of the current node unilt we find a node that has at least one children.

Output
Next Right of 8 is 2
Next Right of 3 is 4
Comment