Depth of the deepest odd level node in Binary Tree | C ++ program to find depth of the deepest odd level node ; A Tree node ; Utility function to create a new node ; Utility function which returns whether the current node is a leaf or not ; function to return the longest odd level depth if it exists otherwise 0 ; Base case return from here ; increment current level ; if curr_level is odd and its a leaf node ; A wrapper over deepestOddLevelDepth ( ) ; 10 / \ 28 13 / \ 14 15 / \ 23 24 Let us create Binary Tree shown in above example
#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 ) ; } bool isleaf ( Node * curr_node ) { return ( curr_node -> left == NULL && curr_node -> right == NULL ) ; } int deepestOddLevelDepthUtil ( Node * curr_node , int curr_level ) { if ( curr_node == NULL ) return 0 ; curr_level += 1 ; if ( curr_level % 2 != 0 && isleaf ( curr_node ) ) return curr_level ; return max ( deepestOddLevelDepthUtil ( curr_node -> left , curr_level ) , deepestOddLevelDepthUtil ( curr_node -> right , curr_level ) ) ; } int deepestOddLevelDepth ( Node * curr_node ) { return deepestOddLevelDepthUtil ( curr_node , 0 ) ; } int main ( ) { Node * root = newNode ( 10 ) ; root -> left = newNode ( 28 ) ; root -> right = newNode ( 13 ) ; root -> right -> left = newNode ( 14 ) ; root -> right -> right = newNode ( 15 ) ; root -> right -> right -> left = newNode ( 23 ) ; root -> right -> right -> right = newNode ( 24 ) ; cout << deepestOddLevelDepth ( root ) << endl ; return 0 ; }