Count even paths in Binary Tree | A Tree node ; Utility function to create a new node ; Utility function to count the even path in a given Binary tree ; Base Condition , when node pointer becomes null or node value is odd ; Increment count when encounter leaf node with all node value even ; Left recursive call , and save the value of count ; Right recursive call , and return value of count ; Function to count the even paths in a given Binary tree ; Function call with count = 0 ; Tree ; Function call
class Node { constructor ( key ) { this . key = key ; this . left = this . right = null ; } } function evenPaths ( node , count ) { if ( node == null || ( node . key % 2 != 0 ) ) { return count ; } if ( node . left == null && node . right == null ) { count ++ ; } count = evenPaths ( node . left , count ) ; return evenPaths ( node . right , count ) ; } function countEvenPaths ( node ) { return evenPaths ( node , 0 ) ; } let root = new Node ( 12 ) ; root . left = new Node ( 13 ) ; root . right = new Node ( 12 ) ; root . right . left = new Node ( 14 ) ; root . right . right = new Node ( 16 ) ; root . right . left . left = new Node ( 21 ) ; root . right . left . right = new Node ( 22 ) ; root . right . right . left = new Node ( 22 ) ; root . right . right . right = new Node ( 24 ) ; root . right . right . right . left = new Node ( 8 ) ; document . write ( countEvenPaths ( root ) ) ;