Maximum sum from a tree with adjacent levels not allowed | Tree node class for Binary Tree representation ; Recursive function to find the maximum sum returned for a root node and its grandchildren ; Returns maximum sum with adjacent levels not allowed . This function mainly uses getSumAlternate ( ) ; We compute sum of alternate levels starting first level and from second level . And return maximum of two values . ; Driver code
class Node { constructor ( data ) { this . data = data ; this . left = this . right = null ; } } function getSumAlternate ( root ) { if ( root == null ) return 0 ; let sum = root . data ; if ( root . left != null ) { sum += getSum ( root . left . left ) ; sum += getSum ( root . left . right ) ; } if ( root . right != null ) { sum += getSum ( root . right . left ) ; sum += getSum ( root . right . right ) ; } return sum ; } function getSum ( root ) { if ( root == null ) return 0 ; return Math . max ( getSumAlternate ( root ) , ( getSumAlternate ( root . left ) + getSumAlternate ( root . right ) ) ) ; } let root = new Node ( 1 ) ; root . left = new Node ( 2 ) ; root . right = new Node ( 3 ) ; root . right . left = new Node ( 4 ) ; root . right . left . right = new Node ( 5 ) ; root . right . left . right . left = new Node ( 6 ) ; document . write ( getSum ( root ) ) ;