Count of nodes which are at a distance X from root and leaves | C ++ implementation of the approach ; Function to find the count of the required nodes ; Height of the complete binary tree with n nodes ; If X > height then no node can be present at that level ; Corner case ; Maximum total nodes that are possible in complete binary tree with height h ; Nodes at the last level ; To store the count of nodes x dist away from root ; To store the count of nodes x dist away from leaf ; If X = h then print nodes at last level else nodes at Xth level ; 2 ^ X ; Number of left leaf nodes at ( h - 1 ) th level observe that if nodes are not present at last level then there are a / 2 leaf nodes at ( h - 1 ) th level ; If X = h then print leaf nodes at the last h level + leaf nodes at ( h - 1 ) th level ; First calculate nodes for leaves present at height h ; Then calculate nodes for leaves present at height h - 1 ; Add both the resuls ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void countNodes ( int N , int X ) { int height = floor ( log2 ( N ) ) ; if ( X > height ) { cout << "0 STRNEWLINE 0" ; return ; } if ( N == 1 ) { cout << "1 STRNEWLINE 1" ; return ; } int max_total_nodes = ( 1 << ( height + 1 ) ) - 1 ; int nodes_last_level = ( 1 << height ) - ( max_total_nodes - N ) ; int from_root ; int from_leaf ; if ( X == height ) from_root = nodes_last_level ; else from_root = 1 << X ; int left_leaf_nodes = ( ( 1 << height ) - nodes_last_level ) / 2 ; if ( X == 0 ) { from_leaf = nodes_last_level + left_leaf_nodes ; } else { int i = X ; while ( nodes_last_level > 1 && i > 0 ) { nodes_last_level = ceil ( ( float ) nodes_last_level / ( float ) 2 ) ; i -- ; } from_leaf = nodes_last_level ; i = X ; while ( left_leaf_nodes > 1 && i > 0 ) { left_leaf_nodes = ceil ( ( float ) left_leaf_nodes / ( float ) 2 ) ; i -- ; } from_leaf += left_leaf_nodes ; } cout << from_root << endl << from_leaf ; } int main ( ) { int N = 38 , X = 3 ; countNodes ( N , X ) ; return 0 ; }