Given a Binary Search Tree with two of the nodes of the Binary Search Tree (BST) swapped. The task is to fix (or correct) the BST.
Note: The BST will not have duplicates.
Input Tree: 10 / \ 5 8 / \ 2 20 In the above tree, nodes 20 and 8 must be swapped to fix the tree. Following is the output tree 10 / \ 5 20 / \ 2 8
- Traverse the BST in In-order fashion and store the nodes in a vector.
- Then this vector is sorted after creating a copy of it.
- Use Insertion sort as it works the best and fastest when the array is almost sorted. As in this problem, only two elements will be displaced so Insertion sort here will work in linear time.
- After sorting, compare the sorted vector and the copy of the vector created earlier, by this, find out the error-some nodes and fix them by finding them in the tree and exchanging them.
Below is the implementation of above approach:
Time Complexity: O(N)
Auxiliary Space: O(N)
where N is the number of nodes in the Binary Tree.
- Two nodes of a BST are swapped, correct the BST
- Sort an almost sorted array where only two elements are swapped
- Count of elements which are not at the correct position
- Splitting starting N nodes into new Circular Linked List while preserving the old nodes
- Subtree of all nodes in a tree using DFS
- Shortest distance between two nodes in BST
- Nodes from given two BSTs with sum equal to X
- Count BST nodes that lie in a given range
- Sum of cousin nodes of a given node in a BST
- Maximum element between two nodes of BST
- Sum of all odd frequency nodes of the Linked List
- Product of all nodes in a Binary Tree
- Sum of the alternate nodes of linked list
- Print Leaf Nodes at a given Level
- Sum of all the Boundary Nodes of a Binary Tree
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : Akanksha_Rai