Connect Nodes at the Same Level

Given a binary tree where each node has at most two children, your task is to connect all adjacent nodes at the same level. You should populate each node's 'next' pointer to its next right node. If there is no next right node, set the 'next' pointer to NULL. Initially, all 'next' pointers are NULL.

The node structure is defined as follows:

class BinaryTreeNode { int data; // Value of the node. BinaryTreeNode *left; // Pointer to left child node. BinaryTreeNode *right; // Pointer to right child node. BinaryTreeNode *next; // Pointer to next right node at same level. }

Example:

The left image shows the initial binary tree and the right image shows the binary tree after connecting adjacent nodes at the same level.

alt text

Connections would be as follows:

The 'next' pointer of the node with value 2 is connected to the node with value 3. The 'next' pointer of the node with value 4 is connected to the node with value 5. The 'next' pointer of the node with value 5 is connected to the node with value 6. Nodes with values 1, 3, and 6 have a 'next' pointer value of NULL.

Input:

The first line of input contains an integer ‘T’ denoting the number of test cases.

Then, for each test case, the first line contains elements in level order, separated by spaces. Use -1 for a null node.

Output:

For each test case, output each level's nodes as connected by 'next' pointers, with '#' marking the end of each level.

Constraints:

  • 1 <= T <= 100
  • 1 <= N <= 3000
  • -10^9 <= DATA <= 10^9

Note:

  • The structure of the node is predefined and should not be altered.
  • The root of the tree is known.
  • There is at least one node in the binary tree.
  • Use only constant extra space.
AnswerBot
4d

Connect adjacent nodes at the same level in a binary tree by populating each node's 'next' pointer.

  • Traverse the tree level by level using a queue.

  • For each node, connect it to the next node in the queu...read more

Help your peers!
Add answer anonymously...
Housing.com Software Engineer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter