Print all root to leaf paths with there relative positions | Javascript program to print all root to leaf paths with there relative position ; tree structure ; Function create new node ; Store path information ; Prints given root to leaf path with underscores ; Find the minimum horizontal distance value in current root to leaf path ; Find minimum horizontal distance ; Print the root to leaf path with " _ " that indicate the related position ; Current tree node ; Print underscore ; Print current key ; A utility function print all path from root to leaf working of this function is similar to function of " Print _ vertical _ order " : Print paths of binary tree in vertical order www . geeksforgeeks . org / print - binary - tree - vertical - order - set - 2 / https : ; Base case ; Leaf node ; Add leaf node and then print path ; Store current path information ; Call left sub_tree ; Call left sub_tree ; Base case ; Driver code
let MAX_PATH_SIZE = 1000 ; class Node { constructor ( data ) { this . data = data ; this . left = this . right = null ; } } class PATH { constructor ( Hd , key ) { this . Hd = Hd ; this . key = key ; } } function printPath ( path , size ) { let minimum_Hd = Number . MAX_VALUE ; let p ; for ( let it = 0 ; it < size ; it ++ ) { p = path [ it ] ; minimum_Hd = Math . min ( minimum_Hd , p . Hd ) ; } for ( let it = 0 ; it < size ; it ++ ) { p = path [ it ] ; let noOfUnderScores = Math . abs ( p . Hd - minimum_Hd ) ; for ( let i = 0 ; i < noOfUnderScores ; i ++ ) document . write ( " " ) ; document . write ( p . key + " " ) ; } document . write ( " " ) ; } function printAllPathsUtil ( root , AllPath , HD , order ) { if ( root == null ) return ; if ( root . left == null && root . right == null ) { AllPath [ order ] = new PATH ( HD , root . data ) ; printPath ( AllPath , order + 1 ) ; return ; } AllPath [ order ] = new PATH ( HD , root . data ) ; printAllPathsUtil ( root . left , AllPath , HD - 1 , order + 1 ) ; printAllPathsUtil ( root . right , AllPath , HD + 1 , order + 1 ) ; } function printAllPaths ( root ) { if ( root == null ) return ; let Allpaths = [ ] ; for ( let i = 0 ; i < MAX_PATH_SIZE ; i ++ ) { Allpaths . push ( new PATH ( ) ) ; } printAllPathsUtil ( root , Allpaths , 0 , 0 ) ; } let root = new Node ( ' ' ) ; root . left = new Node ( ' ' ) ; root . right = new Node ( ' ' ) ; root . left . left = new Node ( ' ' ) ; root . left . right = new Node ( ' ' ) ; root . right . left = new Node ( ' ' ) ; root . right . right = new Node ( ' ' ) ; printAllPaths ( root ) ;