Sum of nodes on the longest path from root to leaf node | Java implementation to find the sum of nodes on the longest path from root to leaf node ; Node of a binary tree ; function to find the sum of nodes on the longest path from root to leaf node ; if true , then we have traversed a root to leaf path ; update maximum length and maximum sum according to the given conditions ; recur for left subtree ; recur for right subtree ; utility function to find the sum of nodes on the longest path from root to leaf node ; if tree is NULL , then sum is 0 ; finding the maximum sum ' maxSum ' for the maximum length root to leaf path ; required maximum sum ; Driver program to test above ; binary tree formation ; 4 ; / \ ; 2 5 ; / \ / \ ; 7 1 2 3 ; 6
public class GFG { static class Node { int data ; Node left , right ; Node ( int data ) { this . data = data ; left = null ; right = null ; } } static int maxLen ; static int maxSum ; static void sumOfLongRootToLeafPath ( Node root , int sum , int len ) { if ( root == null ) { if ( maxLen < len ) { maxLen = len ; maxSum = sum ; } else if ( maxLen == len && maxSum < sum ) maxSum = sum ; return ; } sumOfLongRootToLeafPath ( root . left , sum + root . data , len + 1 ) ; sumOfLongRootToLeafPath ( root . right , sum + root . data , len + 1 ) ; } static int sumOfLongRootToLeafPathUtil ( Node root ) { if ( root == null ) return 0 ; maxSum = Integer . MIN_VALUE ; maxLen = 0 ; sumOfLongRootToLeafPath ( root , 0 , 0 ) ; return maxSum ; } public static void main ( String args [ ] ) { Node root = new Node ( 4 ) ; root . left = new Node ( 2 ) ; root . right = new Node ( 5 ) ; root . left . left = new Node ( 7 ) ; root . left . right = new Node ( 1 ) ; root . right . left = new Node ( 2 ) ; root . right . right = new Node ( 3 ) ; root . left . right . left = new Node ( 6 ) ; System . out . println ( " Sum ▁ = ▁ " + sumOfLongRootToLeafPathUtil ( root ) ) ; } }