Connect Nodes at Same Level Problem Statement

An assignment is to link adjacent nodes at the same level in a binary tree. Each node in a binary tree has at most two children (left and right) and a next pointer to the next right node at the same level. If there is no next right node, the next pointer should be set to NULL. Initially, all next pointers are NULL.

Input:

The first line of input consists of an integer ‘T’, representing the number of test cases.
For each test case, the first line contains elements in level order format, separated by spaces. If a node is NULL, it is represented by -1.

Example tree input:
1 2 3 4 -1 5 6 -1 7 -1 -1 -1 -1 -1 -1

Output:

For each test case, produce the level order as connected by next pointers, with '#' marking the end of each level.

Example output:
1 # 2 3 # 4 5 6 # 7 #

Example:

Input:
1
1 2 3 4 -1 5 6 -1 7 -1 -1 -1 -1 -1 -1
Output:
1 # 2 3 # 4 5 6 # 7 #

Constraints:

  • 1 <= T <= 100
  • 1 <= N <= 3000
  • -109 <= DATA <= 109

Ensure an efficient operation given N node constraints in each tree and constant space usage aside from input constraints.

AnswerBot
4mo

Connect adjacent nodes at the same level in a binary tree by setting next pointers.

  • Traverse the tree level by level using a queue.

  • For each level, connect nodes using the next pointer.

  • Set the next poin...read more

Help your peers!
Select
Add answer anonymously...

AlphaSense Software Developer interview questions & answers

A Software Developer was asked 11mo agoQ. Write a program to print the last 10 lines of a file, and configure it to run ev...read more
A Software Developer was asked 11mo agoQ. Let's discuss a system design scenario: Imagine an API that takes a long time to...read more
A Software Developer was asked Q. What is a peer-to-peer connection?

Popular interview questions of Software Developer

A Software Developer was asked 11mo agoQ1. Let's discuss a system design scenario: Imagine an API that takes a long time to...read more
A Software Developer was asked Q2. What is a peer-to-peer connection?
A Software Developer was asked Q3. Median of Two Sorted Arrays Given two sorted arrays A and B of sizes N and M, fi...read more
AlphaSense Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+

Reviews

10L+

Interviews

4 Cr+

Salaries

1.5 Cr+

Users

Contribute to help millions

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

Follow Us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
Profile Image
Hello, Guest
AmbitionBox Employee Choice Awards 2025
Winners announced!
awards-icon
Contribute to help millions!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos
Add office benefits
Add office benefits