Count even paths in Binary Tree | Java program for the above approach ; 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 ; Driver Code ; Tree ; Function call
import java . util . * ; class GFG { static class Node { int key ; Node left , right ; } ; static Node newNode ( int key ) { Node temp = new Node ( ) ; temp . key = key ; temp . left = temp . right = null ; return ( temp ) ; } static int evenPaths ( Node node , int 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 ) ; } static int countEvenPaths ( Node node ) { return evenPaths ( node , 0 ) ; } public static void main ( String args [ ] ) { Node root = newNode ( 12 ) ; root . left = newNode ( 13 ) ; root . right = newNode ( 12 ) ; root . right . left = newNode ( 14 ) ; root . right . right = newNode ( 16 ) ; root . right . left . left = newNode ( 21 ) ; root . right . left . right = newNode ( 22 ) ; root . right . right . left = newNode ( 22 ) ; root . right . right . right = newNode ( 24 ) ; root . right . right . right . left = newNode ( 8 ) ; System . out . println ( countEvenPaths ( root ) ) ; } }