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:

    struct TreeLinkNode {
      TreeLinkNode *left;
      TreeLinkNode *right;
      TreeLinkNode *next;
    }

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.
 * public class TreeLinkNode {
 *     int val;
 *     TreeLinkNode left, right, next;
 *     TreeLinkNode(int x) { val = x; }
 * }
 */
public class Solution {
    public void connect(TreeLinkNode root) {
        if(root.left ==null && root.right == null) root.next=null;
        Queue<TreeLinkNode> queue = new LinkedList<TreeLinkNode>();
        queue.offer(root);
        while(!queue.isEmpty()){
            int size = queue.size();
            for(int i=0; i<size; i++){
                TreeLinkNode curr = queue.poll();
                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
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Add two numbers in Scala - The Coding Shala

New Year Chaos Solution - The Coding Shala

Richest Customer Wealth LeetCode Solution - The Coding Shala