Ninja And The Tree Problem Statement

Ninja, while learning Binary Search Trees (BST), accidentally swapped two nodes in her self-constructed BST. Your task is to help Ninja by correcting the BST so that all properties of a BST are satisfied.

Input:

The first line contains an integer 'T' which denotes the number of test cases.

For each test case, a single line contains the elements of the tree in level order form, separated by a single space. If a node doesn't have a left or right child, take -1 in its place.

Output:

For each test case, output the corrected Binary Search Tree in level order form. Each test case output should be on a separate line.

Example:

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

The input in level order first describes the root node, followed by its children from left to right, continuing level by level. Nodes without children are represented with -1.

Constraints:

  • 1 <= T <= 100
  • 2 <= N <= 5000, where 'N' is the number of nodes.
  • 0 <= X <= 2^31 - 1, where 'X' is the value at a node.
  • Time limit: 1 second
Note:
The sequence of input ends when all nodes at the last level are null (-1). You are not required to print anything; it has already been handled. Just implement the function to return the corrected BST.
AnswerBot
2d

The task is to correct a Binary Search Tree by swapping two nodes in the tree.

  • Parse the input level order tree and construct the BST

  • Identify the two nodes that are swapped incorrectly

  • Swap the values o...read more

Help your peers!
Add answer anonymously...
American Express Software Developer 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