Maximize sum of path from the Root to a Leaf node in N | C # program for the above approach ; Stores the maximum sum of a path ; Structure of a node in the tree ; Utility function to create a new node in the tree ; Recursive function to calculate the maximum sum in a path using DFS ; If current node is a leaf node ; Traversing all children of the current node ; Recursive call for all the children nodes ; Given Generic Tree ; Function Call
using System ; using System . Collections ; using System . Collections . Generic ; class GFG { static int maxSumPath = 0 ; class Node { public int val ; public List < Node > child ; public Node ( int key ) { val = key ; child = new List < Node > ( ) ; } } static Node newNode ( int key ) { Node temp = new Node ( key ) ; return temp ; } static void DFS ( Node root , int sum ) { if ( root . child . Count == 0 ) { maxSumPath = Math . Max ( maxSumPath , sum ) ; return ; } for ( int i = 0 ; i < root . child . Count ; i ++ ) { DFS ( root . child [ i ] , sum + root . child [ i ] . val ) ; } } static void Main ( ) { Node root = newNode ( 1 ) ; ( root . child ) . Add ( newNode ( 2 ) ) ; ( root . child ) . Add ( newNode ( 3 ) ) ; ( root . child [ 0 ] . child ) . Add ( newNode ( 4 ) ) ; ( root . child [ 1 ] . child ) . Add ( newNode ( 6 ) ) ; ( root . child [ 0 ] . child ) . Add ( newNode ( 5 ) ) ; ( root . child [ 1 ] ) . child . Add ( newNode ( 7 ) ) ; ( root . child [ 1 ] . child ) . Add ( newNode ( 8 ) ) ; DFS ( root , root . val ) ; Console . Write ( maxSumPath ) ; } }