Count of exponential paths in a Binary Tree | Structure of a Tree node ; Function to create a new node ; Function to find x ; Take log10 of n ; Log ( n ) with base i ; Raising i to the power p ; Function to check whether the given node equals to x ^ y for some y > 0 ; Take logx ( n ) with base x ; Utility function to count the exponent path in a given Binary tree ; Base Condition , when node pointer becomes null or node value is not a number of pow ( x , y ) ; Increment count when encounter leaf node ; Left recursive call save the value of count ; Right recursive call and return value of count ; Function to count exponential paths ; Create Tree ; Retrieve the value of x ; Function call
class Node { constructor ( key ) { this . left = null ; this . right = null ; this . key = key ; } } function newNode ( key ) { let temp = new Node ( key ) ; return ( temp ) ; } function find_x ( n ) { if ( n == 1 ) return 1 ; let num , den , p ; num = Math . log10 ( n ) ; let x = 0 , no = 0 ; for ( let i = 2 ; i <= n ; i ++ ) { den = Math . log10 ( i ) ; p = num / den ; no = parseInt ( Math . pow ( i , parseInt ( p , 10 ) ) , 10 ) ; if ( Math . abs ( no - n ) < 1e-6 ) { x = i ; break ; } } return x ; } function is_key ( n , x ) { let p ; p = Math . log10 ( n ) / Math . log10 ( x ) ; let no = parseInt ( Math . pow ( x , parseInt ( p , 10 ) ) , 10 ) ; if ( n == no ) return true ; return false ; } function evenPaths ( node , count , x ) { if ( node == null || ! is_key ( node . key , x ) ) { return count ; } if ( node . left == null && node . right == null ) { count ++ ; } count = evenPaths ( node . left , count , x ) ; return evenPaths ( node . right , count , x ) ; } function countExpPaths ( node , x ) { return evenPaths ( node , 0 , x ) ; } let root = newNode ( 27 ) ; root . left = newNode ( 9 ) ; root . right = newNode ( 81 ) ; root . left . left = newNode ( 3 ) ; root . left . right = newNode ( 10 ) ; root . right . left = newNode ( 70 ) ; root . right . right = newNode ( 243 ) ; root . right . right . left = newNode ( 81 ) ; root . right . right . right = newNode ( 909 ) ; let x = find_x ( root . key ) ; document . write ( countExpPaths ( root , x ) ) ;