Reverse tree path | Java program to Reverse Tree path ; A Binary Tree Node ; class for int values ; ' data ' is input . We need to reverse path from root to data . ' level ' is current level . ' temp ' that stores path nodes . ' nextpos ' used to pick next item for reversing . ; return null if root null ; Final condition if the node is found then ; store the value in it 's level ; change the root value with the current next element of the map ; increment in k for the next element ; store the data in perticular level ; We go to right only when left does not contain given data . This way we make sure that correct path node is stored in temp [ ] ; If current node is part of the path , then do reversing . ; return null if not element found ; Reverse Tree path ; store per level data ; it is for replacing the data ; reverse tree path ; INORDER ; Utility function to create a new tree node ; Driver program to test above functions ; Let us create binary tree shown in above diagram ; 7 / \ 6 5 / \ / \ 4 3 2 1 ; Reverse Tree Path ; Traverse inorder
import java . util . * ; class solution { static class Node { int data ; Node left , right ; } ; static class INT { int data ; } ; static Node reverseTreePathUtil ( Node root , int data , Map < Integer , Integer > temp , int level , INT nextpos ) { if ( root == null ) return null ; if ( data == root . data ) { temp . put ( level , root . data ) ; root . data = temp . get ( nextpos . data ) ; nextpos . data ++ ; return root ; } temp . put ( level , root . data ) ; Node left , right = null ; left = reverseTreePathUtil ( root . left , data , temp , level + 1 , nextpos ) ; if ( left == null ) right = reverseTreePathUtil ( root . right , data , temp , level + 1 , nextpos ) ; if ( left != null right != null ) { root . data = temp . get ( nextpos . data ) ; nextpos . data ++ ; return ( left != null ? left : right ) ; } return null ; } static void reverseTreePath ( Node root , int data ) { Map < Integer , Integer > temp = new HashMap < Integer , Integer > ( ) ; INT nextpos = new INT ( ) ; nextpos . data = 0 ; reverseTreePathUtil ( root , data , temp , 0 , nextpos ) ; } static void inorder ( Node root ) { if ( root != null ) { inorder ( root . left ) ; System . out . print ( root . data + " ▁ " ) ; inorder ( root . right ) ; } } static Node newNode ( int data ) { Node temp = new Node ( ) ; temp . data = data ; temp . left = temp . right = null ; return temp ; } public static void main ( String args [ ] ) { Node root = newNode ( 7 ) ; root . left = newNode ( 6 ) ; root . right = newNode ( 5 ) ; root . left . left = newNode ( 4 ) ; root . left . right = newNode ( 3 ) ; root . right . left = newNode ( 2 ) ; root . right . right = newNode ( 1 ) ; int data = 4 ; reverseTreePath ( root , data ) ; inorder ( root ) ; } }