Fixing a Swapped Binary Search Tree

Given a Binary Search Tree (BST) where two nodes have been swapped by mistake, your task is to restore or fix the BST without changing its structure.

Input:

The first line of input contains an integer T, representing the number of test cases.
The first line of each test case contains the elements of the tree in level order form, separated by spaces in a single line. The value -1 denotes a null node.

Output:

For each test case, output the level order traversal of the restored tree in a separate line.

Example:

Input:
1
20 30 35 5 15 10 42 -1 -1 13 -1 -1 -1 -1 -1 -1 -1
Output:
20 5 35 30 15 10 42 13

Constraints:

  • 1 <= T <= 100
  • 1 <= N <= 10^3
  • 0 <= data <= 10^9 where 'data' denotes the value of the nodes in the given tree.
  • Time limit: 1 second

Note:

The BST will not contain duplicate nodes. The input format description provides clarity on how level order input is structured. No extra space other than the recursion stack should be used to solve this problem.

AnswerBot
4mo

Restore a Binary Search Tree by fixing two swapped nodes without changing its structure.

  • Identify the two nodes that are swapped by mistake in the BST.

  • Swap the values of the two identified nodes to res...read more

Help your peers!
Select
Add answer anonymously...

Top Software Developer Interview Questions Asked at Oyo Rooms

Q. Given the head of a singly linked list and two integers m and n, reverse the nod...read more
Q. Merge sort algorithm and divide array in the chunks
Q. Position of Right Most Set Bit Determine the position of the rightmost set bit i...read more
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