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.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- 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
- Nodes from given two BSTs with sum equal to X
- 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
- Shortest distance between two nodes in BST
- Sum of cousin nodes of a given node in a BST
- Product of all nodes in a Binary Tree
- Sum of the alternate nodes of linked list
- Check whether the given node is in the path between the nodes U and V
- Sum of all odd frequency nodes of the Linked List
- Print Leaf Nodes at a given Level
- Sum of all the Boundary Nodes of a Binary Tree
- Number of special nodes in an n-ary tree
- Count greater nodes in AVL tree
Improved By : Akanksha_Rai