text: Maximum sum from a tree with adjacent levels not allowed | C # code for max sum 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
code: using System ; class GFG { public class Node { public int data ; public Node left , right ; public Node ( int item ) { data = item ; left = right = null ; } } public static int getSumAlternate ( Node root ) { if ( root == null ) return 0 ; int 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 ; } public static int getSum ( Node root ) { if ( root == null ) return 0 ; return Math . Max ( getSumAlternate ( root ) , ( getSumAlternate ( root . left ) + getSumAlternate ( root . right ) ) ) ; } public static void Main ( ) { Node 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 ) ; Console . WriteLine ( getSum ( root ) ) ; } }