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.
Examples:
Input :
Output :
Explanation: The preorder traversal of given binary tree is 10 8 3 5 2.
[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:
C++
// C++ code to modify binary tree for// traversal using only right pointer#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intx){data=x;left=right=nullptr;}};// Function to modify treeNode*modifytree(Node*root){Node*right=root->right;Node*rightMost=root;// if the left tree existsif(root->left){// get the right-most of the// original left subtreerightMost=modifytree(root->left);// set root right to left subtreeroot->right=root->left;root->left=nullptr;}// if the right subtree does// not exists we are done!if(!right)returnrightMost;// set right pointer of right-most// of the original left subtreerightMost->right=right;// modify the rightsubtreerightMost=modifytree(right);returnrightMost;}voidprintpre(Node*curr){while(curr!=nullptr){cout<<curr->data<<" ";curr=curr->right;}}intmain(){// Constructed binary tree is// 10// / \ // 8 2// / \ // 3 5 Node*root=newNode(10);root->left=newNode(8);root->right=newNode(2);root->left->left=newNode(3);root->left->right=newNode(5);modifytree(root);printpre(root);return0;}
Java
// Java code to modify binary tree for traversal// using only right pointerclassNode{intdata;Nodeleft,right;publicNode(intx){data=x;left=right=null;}}classGfG{// Function to modify treestaticNodemodifytree(Noderoot){Noderight=root.right;NoderightMost=root;// If the left tree existsif(root.left!=null){// Get the right-most of the original left// subtreerightMost=modifytree(root.left);// Set root right to left subtreeroot.right=root.left;root.left=null;}// If the right subtree does not// exist we are done!if(right==null)returnrightMost;// Set right pointer of right-most of the original// left subtreerightMost.right=right;// Modify the right subtreerightMost=modifytree(right);returnrightMost;}staticvoidprintpre(Nodecurr){while(curr!=null){System.out.print(curr.data+" ");curr=curr.right;}}publicstaticvoidmain(String[]args){// Constructed binary tree is// 10// / \// 8 2// / \ // 3 5Noderoot=newNode(10);root.left=newNode(8);root.right=newNode(2);root.left.left=newNode(3);root.left.right=newNode(5);modifytree(root);printpre(root);}}
Python
# Python code to modify binary tree for traversal using# only right pointerclassNode:def__init__(self,data):self.data=dataself.left=Noneself.right=None# Function to modify treedefmodifytree(root):right=root.rightright_most=root# If the left tree existsifroot.left:# Get the right-most of the original # left subtreeright_most=modifytree(root.left)# Set root right to left subtreeroot.right=root.leftroot.left=None# If the right subtree does not exist# we are done!ifnotright:returnright_most# Set right pointer of right-most of the # original left subtreeright_most.right=right# Modify the right subtreeright_most=modifytree(right)returnright_mostdefprintpre(curr):whilecurr:print(curr.data,end=" ")curr=curr.rightif__name__=="__main__":# Constructed binary tree is# 10# / \# 8 2# / \# 3 5root=Node(10)root.left=Node(8)root.right=Node(2)root.left.left=Node(3)root.left.right=Node(5)modifytree(root)printpre(root)
C#
// C# code to modify binary tree for traversal using only// right pointerusingSystem;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=right=null;}}classGfG{// Function to modify treestaticNodemodifytree(Noderoot){Noderight=root.right;NoderightMost=root;// If the left tree existsif(root.left!=null){// Get the right-most of the original left// subtreerightMost=modifytree(root.left);// Set root right to left subtreeroot.right=root.left;root.left=null;}// If the right subtree does // not exist we are done!if(right==null)returnrightMost;// Set right pointer of right-most of the original// left subtreerightMost.right=right;// Modify the right subtreerightMost=modifytree(right);returnrightMost;}staticvoidprintpre(Nodecurr){while(curr!=null){Console.Write(curr.data+" ");curr=curr.right;}}staticvoidMain(string[]args){// Constructed binary tree is// 10// / \// 8 2// / \ // 3 5Noderoot=newNode(10);root.left=newNode(8);root.right=newNode(2);root.left.left=newNode(3);root.left.right=newNode(5);modifytree(root);printpre(root);}}
JavaScript
// JavaScript code to modify binary tree for traversal using// only right pointerclassNode{constructor(data){this.data=data;this.left=null;this.right=null;}}// Function to modify treefunctionmodifytree(root){letright=root.right;letrightMost=root;// If the left tree existsif(root.left){// Get the right-most of the original// left subtreerightMost=modifytree(root.left);// Set root right to left subtreeroot.right=root.left;root.left=null;}// If the right subtree does not // exist we are done!if(!right)returnrightMost;// Set right pointer of right-most of//the original left subtreerightMost.right=right;// Modify the right subtreerightMost=modifytree(right);returnrightMost;}functionprintpre(curr){while(curr!=null){console.log(curr.data+" ");curr=curr.right;}}letroot=newNode(10);root.left=newNode(8);root.right=newNode(2);root.left.left=newNode(3);root.left.right=newNode(5);modifytree(root);printpre(root);
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:
C++
// C++ code to modify binary tree for// traversal using only right pointer#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intx){data=x;left=right=nullptr;}};// An iterative process to set the right// pointer of Binary treevoidmodifytree(Node*root){if(root==nullptr)return;// Create an empty stack and // push root to itstack<Node*>nodeStack;nodeStack.push(root);Node*pre=nullptr;while(nodeStack.empty()==false){// Pop the top item from stackNode*node=nodeStack.top();nodeStack.pop();// Push right and left children of// the popped node to stackif(node->right)nodeStack.push(node->right);if(node->left)nodeStack.push(node->left);// check if some previous node// existsif(pre!=nullptr){// set the right pointer of// previous node to currentpre->right=node;}pre=node;}}voidprintpre(Node*root){while(root!=nullptr){cout<<root->data<<" ";root=root->right;}}intmain(){// Constructed binary tree is// 10// / \ // 8 2// / \ // 3 5 Node*root=newNode(10);root->left=newNode(8);root->right=newNode(2);root->left->left=newNode(3);root->left->right=newNode(5);modifytree(root);printpre(root);return0;}
Java
// Java code to modify binary tree for// traversal using only right pointerimportjava.util.Stack;classNode{intdata;Nodeleft,right;publicNode(intx){data=x;left=right=null;}}classGfG{// An iterative process to set the right// pointer of Binary treestaticvoidmodifytree(Noderoot){if(root==null)return;// Create an empty stack and push // root to itStack<Node>nodeStack=newStack<>();nodeStack.push(root);Nodepre=null;while(!nodeStack.isEmpty()){// Pop the top item from stackNodenode=nodeStack.pop();// Push right and left children of the// popped node to stackif(node.right!=null)nodeStack.push(node.right);if(node.left!=null)nodeStack.push(node.left);// Check if some previous node existsif(pre!=null){// Set the right pointer of// previous node to currentpre.right=node;}pre=node;}}staticvoidprintpre(Noderoot){while(root!=null){System.out.print(root.data+" ");root=root.right;}}publicstaticvoidmain(String[]args){// Constructed binary tree is// 10// / \// 8 2// / \ // 3 5 Noderoot=newNode(10);root.left=newNode(8);root.right=newNode(2);root.left.left=newNode(3);root.left.right=newNode(5);modifytree(root);printpre(root);}}
Python
# Python code to modify binary tree # for traversal using only right pointerclassNode:def__init__(self,data):self.data=dataself.left=Noneself.right=None# An iterative process to set the right# pointer of Binary treedefmodifytree(root):ifrootisNone:return# Create an empty stack and push# root to itnodeStack=[]nodeStack.append(root)pre=NonewhilenodeStack:# Pop the top item from stacknode=nodeStack.pop()# Push right and left children of # the popped node to stackifnode.right:nodeStack.append(node.right)ifnode.left:nodeStack.append(node.left)# Check if some previous node existsifpreisnotNone:# Set the right pointer of # previous node to currentpre.right=nodepre=nodedefprintpre(root):whilerootisnotNone:print(root.data,end=" ")root=root.rightif__name__=="__main__":# Constructed binary tree is# 10# / \# 8 2# / \ # 3 5 root=Node(10)root.left=Node(8)root.right=Node(2)root.left.left=Node(3)root.left.right=Node(5)modifytree(root)printpre(root)
C#
// C# code to modify binary tree for // traversal using only right pointerusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=right=null;}}classGfG{// An iterative process to set the // right pointer of Binary treestaticvoidmodifytree(Noderoot){if(root==null)return;// Create an empty stack and push root to itStack<Node>nodeStack=newStack<Node>();nodeStack.Push(root);Nodepre=null;while(nodeStack.Count>0){// Pop the top item from stackNodenode=nodeStack.Pop();// Push right and left children of// the popped node to stackif(node.right!=null)nodeStack.Push(node.right);if(node.left!=null)nodeStack.Push(node.left);// Check if some previous node existsif(pre!=null){pre.right=node;}pre=node;}}staticvoidprintpre(Noderoot){while(root!=null){Console.Write(root.data+" ");root=root.right;}}staticvoidMain(string[]args){// Constructed binary tree is// 10// / \// 8 2// / \ // 3 5 Noderoot=newNode(10);root.left=newNode(8);root.right=newNode(2);root.left.left=newNode(3);root.left.right=newNode(5);modifytree(root);printpre(root);}}
JavaScript
// JavaScript code to modify binary tree // for traversal using only right pointerclassNode{constructor(data){this.data=data;this.left=null;this.right=null;}}// An iterative process to set the right// pointer of Binary treefunctionmodifytree(root){if(root===null)return;// Create an empty stack and push// root to itconstnodeStack=[];nodeStack.push(root);letpre=null;while(nodeStack.length>0){// Pop the top item from stackconstnode=nodeStack.pop();// Push right and left children of // the popped node to stackif(node.right!==null)nodeStack.push(node.right);if(node.left!==null)nodeStack.push(node.left);// Check if some previous node existsif(pre!==null){pre.right=node;}pre=node;}}functionprintpre(root){while(root!==null){console.log(root.data+" ");root=root.right;}}constroot=newNode(10);root.left=newNode(8);root.right=newNode(2);root.left.left=newNode(3);root.left.right=newNode(5);modifytree(root);printpre(root);