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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Two nodes of a BST are swapped, correct the BST
- Sort an almost sorted array where only two elements are swapped
- Check if the array can be sorted only if the elements on given positions can be 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
- Common nodes in the inorder sequence of a tree between given two nodes in O(1) space
- Shortest distance between two nodes in BST
- Subtree of all nodes in a tree using DFS
- Sum of cousin nodes of a given node in a BST
- Count BST nodes that lie in a given range
- Maximum element between two nodes of BST
- Nodes from given two BSTs with sum equal to X
- Sum of the alternate nodes of linked list
- Product of all nodes in a Binary Tree
- Number of special nodes in an n-ary tree
- Sum of all the Boundary Nodes of a Binary Tree
- Print Leaf Nodes at a given Level
- Check if two nodes are on same path in a tree | Set 2
- Count greater nodes in AVL tree
- Sum of all odd frequency nodes of the Linked List
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