Modify a binary tree to get preorder traversal using right pointers only | Java code to modify binary tree for traversal using only right pointer ; A binary tree node has data , left child and right child ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; An iterative process to set the right pointer of Binary tree ; Base Case ; Create an empty stack and push root to it ; Pop all items one by one . Do following for every popped item a ) print it b ) push its right child c ) push its left child Note that right child is pushed first so that left is processed first ; Pop the top item from stack ; Push right and left children of the popped node to stack ; check if some previous node exists ; set the right pointer of previous node to currrent ; set previous node as current node ; printing using right pointer only ; Driver code ; Constructed binary tree is 10 / \ 8 2 / \ 3 5
import java . util . * ; class GfG { static class Node { int data ; Node left ; Node right ; } static Node newNode ( int data ) { Node node = new Node ( ) ; node . data = data ; node . left = null ; node . right = null ; return ( node ) ; } static void modifytree ( Node root ) { if ( root == null ) return ; Stack < Node > nodeStack = new Stack < Node > ( ) ; nodeStack . push ( root ) ; Node pre = null ; while ( nodeStack . isEmpty ( ) == false ) { Node node = nodeStack . peek ( ) ; nodeStack . pop ( ) ; if ( node . right != null ) nodeStack . push ( node . right ) ; if ( node . left != null ) nodeStack . push ( node . left ) ; if ( pre != null ) { pre . right = node ; } pre = node ; } } static void printpre ( Node root ) { while ( root != null ) { System . out . print ( root . data + " ▁ " ) ; root = root . right ; } } public static void main ( String [ ] args ) { 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 ) ; } }