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 ; function that allocates a new node with the given data and null left and right pointers . ; Function to modify tree ; if the left tree exists ; get the right - most of the original left subtree ; set root right to left subtree ; if the right subtree does not exists we are done ! ; set right pointer of right - most of the original left subtree ; modify the rightsubtree ; printing using right pointer only ; Driver cde ; Constructed binary tree is 10 / \ 8 2 / \ 3 5
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 Node modifytree ( Node root ) { Node right = root . right ; Node rightMost = root ; if ( root . left != null ) { rightMost = modifytree ( root . left ) ; root . right = root . left ; root . left = null ; } if ( right == null ) return rightMost ; rightMost . right = right ; rightMost = modifytree ( right ) ; return rightMost ; } 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 ) ; } }