### Connect nodes at the same level in a binary tree - The Coding Shala

Last Updated: 20-Jan-2021
Home >> Interview Questions >> Connect Nodes at the same level in a binary tree

In this post, we will learn how to Connect nodes at the same level in a binary tree and will implement its solution in Java.

## Connect nodes at the same level  in a binary tree

We have given a perfect binary tree, where each node has an extra pointer called next. The next pointer should point to the node on the right side of it on the same level. This problem is known as connecting nodes at the same level.

Given a binary tree:

}

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.

Example:
Given the following perfect binary tree,

1
/    \
2      5
/ \     / \
3  4  6  7

After calling your function, the tree should look like this:

1  -> NULL
/      \
2 ->    5 -> NULL
/ \         /  \
3->4 -> 6->7 -> NULL

## Connect Nodes at the same level in a binary tree Java Program

Approach 1

We can traverse the binary tree in level order using queue and connect the current node to its next node at every level.

Java Program:

Java Code:
/**
* Definition for binary tree with next pointer.
*     int val;
*     TreeLinkNode(int x) { val = x; }
* }
*/
public class Solution {
if(root.left ==null && root.right == null) root.next=null;
queue.offer(root);
while(!queue.isEmpty()){
int size = queue.size();
for(int i=0; i<size; i++){
if(curr.left != null) queue.offer(curr.left);
if(curr.right != null) queue.offer(curr.right);
if(i!=size-1){
curr.next = queue.peek();
}else{
curr.next = null;
}
}
}
}
}

Other Posts You May Like