You have been given a Binary Search Tree of 'N' nodes, where exactly two nodes of the same tree were swapped by mistake.
Your task is to restore or fix the BST, without changing its structure and return the root of the corrected BST.
Note:
Given BST will not contain duplicates.
A Binary Search Tree (BST) whose 2 nodes have been swapped is shown below.

After swapping the incorrect nodes:

Can you do this without using any extra space?
The first line contains elements in the level order form. The input consists of values of nodes separated by a single space in a single line. In case a node is null, we take -1 on its place.
Example :
The input for the tree is depicted in the below image:

1 3 8 5 2 7 -1 -1 -1 -1 -1 -1 -1
Explanation :
Level 1 :
The root node of the tree is 1
Level 2 :
Left child of 1 = 3
Right child of 1 = 8
Level 3 :
Left child of 3 = 5
Right child of 3 = 2
Left child of 8 =7
Right child of 8 = null (-1)
Level 4 :
Left child of 5 = null (-1)
Right child of 5 = null (-1)
Left child of 2 = null (-1)
Right child of 2 = null (-1)
Left child of 7 = null (-1)
Right child of 7 = null (-1)
1
3 8
5 2 7 -1
-1 -1 -1 -1 -1 -1
Note :
1. The first not-null node(of the previous level) is treated as the parent of the first two nodes of the current level. The second not-null node (of the previous level) is treated as the parent node for the next two nodes of the current level and so on.
2. The input ends when all nodes at the last level are null(-1).
3. The above format was just to provide clarity on how the input is formed for a given tree. The sequence will be put together in a single line separated by a single space. Hence, for the above-depicted tree, the input will be given as:
1 3 8 5 2 7 -1 -1 -1 -1 -1 -1 -1
Output Format:
The output contains the 'N' single space-separated level order traversal of the restored tree.
Note:
You don’t have to print anything, it has already been taken care of. Just implement the function.
1 5 -1 -1 3 -1 -1
5 1 3
5 cannot be the left child of 1 as 5 > 1. Swapping 5 and 1 will result in a valid BST.
3 1 4 -1 -1 2 -1 -1 -1
2 1 4 3
1 <= 'N' <= 10^3
0 <= 'data' <= 10^5
where 'N' is the number of nodes and 'data' denotes the node value of the binary tree nodes.
Time limit: 1 sec
Can you do this by storing the inorder traversal of the tree?
The steps are as follows:
Algorithm for storing inorder traversal :
void inorder('ROOT', ‘INORDERTRAVERSAL’)
O(N * log(N)) where ‘N’ is the number of nodes in the given BST.
Since we are traversing the tree for storing the inorder traversal and then we are sorting the array. Storing in order traversal and the final process of updating the values of the nodes can be done in O(N) time. Sorting the array takes O(N * log(N)) time and thus, the final time complexity is O(N + N * log(N) + N) = O(N * log(N)).
O(N), where ‘N’ is the number of nodes of the given BST.
Since we are storing the value of every node of the tree in the array. Thus, the final space complexity is O(N).