Count even paths in Binary Tree | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int key ; struct Node * left , * right ; } ; Node * newNode ( int key ) { Node * temp = new Node ; temp -> key = key ; temp -> left = temp -> right = NULL ; return ( temp ) ; } int evenPaths ( struct Node * node , int count ) { if ( node == NULL || ( node -> key % 2 != 0 ) ) { return count ; } if ( ! node -> left && ! node -> right ) { count ++ ; } count = evenPaths ( node -> left , count ) ; return evenPaths ( node -> right , count ) ; } int countEvenPaths ( struct Node * node ) { return evenPaths ( node , 0 ) ; } int main ( ) { 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 ) ; cout << countEvenPaths ( root ) ; return 0 ; }