Sum of heights of all individual nodes in a binary tree | Java 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 ; Compute the " maxHeight " of a particular Node ; compute the height of each subtree ; use the larger one ; 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
class GfG { static class Node { int data ; Node left ; Node right ; } static int getHeight ( Node Node ) { if ( Node == null ) return 0 ; else { int lHeight = getHeight ( Node . left ) ; int rHeight = getHeight ( Node . right ) ; if ( lHeight > rHeight ) return ( lHeight + 1 ) ; else return ( rHeight + 1 ) ; } } static Node newNode ( int data ) { Node Node = new Node ( ) ; Node . data = data ; Node . left = null ; Node . right = null ; return ( Node ) ; } static int getTotalHeight ( Node root ) { if ( root == null ) return 0 ; return getTotalHeight ( root . left ) + getHeight ( root ) + getTotalHeight ( root . right ) ; } public static void main ( String [ ] args ) { Node root = newNode ( 1 ) ; root . left = newNode ( 2 ) ; root . right = newNode ( 3 ) ; root . left . left = newNode ( 4 ) ; root . left . right = newNode ( 5 ) ; System . out . println ( " Sum ▁ of ▁ heights ▁ of ▁ all ▁ Nodes ▁ = ▁ " + getTotalHeight ( root ) ) ; } }