Sum of heights of all individual nodes in a binary tree | C ++ program to find sum of heights of all nodes in a binary tree ; A binary tree Node has data , pointer to left child and a pointer to right child ; Helper function that allocates a new Node with the given data and NULL left and right pointers . ; Function to sum of heights of individual Nodes Uses Inorder traversal ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left ; struct Node * right ; } ; struct Node * newNode ( int data ) { struct Node * Node = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; Node -> data = data ; Node -> left = NULL ; Node -> right = NULL ; return ( Node ) ; } int getTotalHeightUtil ( struct Node * root , int & sum ) { if ( root == NULL ) return 0 ; int lh = getTotalHeightUtil ( root -> left , sum ) ; int rh = getTotalHeightUtil ( root -> right , sum ) ; int h = max ( lh , rh ) + 1 ; sum = sum + h ; return h ; } int getTotalHeight ( Node * root ) { int sum = 0 ; getTotalHeightUtil ( root , sum ) ; return sum ; } int main ( ) { struct Node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 5 ) ; printf ( " Sum ▁ of ▁ heights ▁ of ▁ all ▁ Nodes ▁ = ▁ % d " , getTotalHeight ( root ) ) ; return 0 ; }