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;
}
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; } } } } }
- Height of a Binary Tree
- Find Minimum Depth of Binary Tree
- How to Invert Binary Tree
- Count Unique Binary Search Trees
- Sort a Linked List using Insertion Sort
Comments
Post a Comment