Modify a binary tree to get preorder traversal using right pointers only
Last Updated : 29 Oct, 2024
Given a binary tree. The task is to modify it in such a way that after modification preorder traversal of it can get only with the right pointers. During modification, we can use right as well as left pointers.
[Expected Approach - 1] Using recursion - O(n) Time and O(h) Space
The idea is to use recursion to transform the tree, the right pointer of the root is made to point to the left subtree. If the node has only a left child, the left child is moved to the right, completing the processing for that node. However, if the node has both left and right children, the original right child is moved to the rightmost node of the left subtree. This process ensures that the entire left subtree is shifted to the right, and the rightmost node of the transformed subtree is returned after the node is processed.
Below is the implementation of the above approach:
Output
10 8 3 5 2
[Expected Approach - 2] Using Iterative Preorder Traversal - O(n) Time and O(n) Space
This can be easily done using Iterative preorder traversal. The idea is to maintain a variable prev which maintains the previous node of the preorder traversal. Every-time a new node is encountered, the node set its right to previous one and prev is made equal to the current node. In the end we will have a sort of linked list whose first element is root then left child then right, so on and so forth.
Below is the implementation of the above approach: