Maximize sum of path from the Root to a Leaf node in N | 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
let maxSumPath = 0 ; class Node { constructor ( key ) { this . child = [ ] ; this . val = key ; } } function newNode ( key ) { let temp = new Node ( key ) ; return temp ; } function DFS ( root , sum ) { if ( root . child . length == 0 ) { maxSumPath = Math . max ( maxSumPath , sum ) ; return ; } for ( let i = 0 ; i < root . child . length ; i ++ ) { DFS ( root . child [ i ] , sum + root . child [ i ] . val ) ; } } let root = newNode ( 1 ) ; ( root . child ) . push ( newNode ( 2 ) ) ; ( root . child ) . push ( newNode ( 3 ) ) ; ( root . child [ 0 ] . child ) . push ( newNode ( 4 ) ) ; ( root . child [ 1 ] . child ) . push ( newNode ( 6 ) ) ; ( root . child [ 0 ] . child ) . push ( newNode ( 5 ) ) ; ( root . child [ 1 ] ) . child . push ( newNode ( 7 ) ) ; ( root . child [ 1 ] . child ) . push ( newNode ( 8 ) ) ; DFS ( root , root . val ) ; document . write ( maxSumPath ) ;