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
- Sum of cousin nodes of a given node in a BST
- Shortest distance between two nodes in BST
- Subtree of all nodes in a tree using DFS
- Count BST nodes that lie in a given range
- Maximum element between two nodes of BST
- Number of special nodes in an n-ary tree
- 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
- Count greater nodes in AVL tree
- Print all odd nodes of Binary Search 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 firstname.lastname@example.org. 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.