Number of subtrees having odd count of even numbers | Java implementation to find number of subtrees having odd count of even numbers ; A binary tree Node ; Helper function that allocates a new Node with the given data and NULL left and right pointers . ;  ; Returns count of subtrees having odd count of even numbers ; base condition ; count even nodes in left subtree ; Add even nodes in right subtree ; Check if root data is an even number ; if total count of even numbers for the subtree is odd ; Total count of even nodes of the subtree ; A wrapper over countRec ( ) ; Driver program to test above ; binary tree formation ; 2 ; / \ ; 1 3 ; / \ / \ ; 4 10 8 5 ; / ; 6
import java . util . * ; class GfG { static class Node { int data ; Node left , right ; } static Node newNode ( int data ) { Node node = new Node ( ) ; node . data = data ; node . left = null ; node . right = null ; return ( node ) ; } static class P { int pcount = 0 ; } static int countRec ( Node root , P p ) { if ( root == null ) return 0 ; int c = countRec ( root . left , p ) ; c += countRec ( root . right , p ) ; if ( root . data % 2 == 0 ) c += 1 ; if ( c % 2 != 0 ) ( p . pcount ) ++ ; return c ; } static int countSubtrees ( Node root ) { P p = new P ( ) ; countRec ( root , p ) ; return p . pcount ; } public static void main ( String [ ] args ) { Node root = newNode ( 2 ) ; root . left = newNode ( 1 ) ; root . right = newNode ( 3 ) ; root . left . left = newNode ( 4 ) ; root . left . right = newNode ( 10 ) ; root . right . left = newNode ( 8 ) ; root . right . right = newNode ( 5 ) ; root . left . right . left = newNode ( 6 ) ; System . out . println ( " Count ▁ = ▁ " + countSubtrees ( root ) ) ; } }