Given a binary tree containing n nodes. The problem is to find the sum of all nodes on the longest path from root to leaf node. If two or more paths compete for the longest path, then the path having maximum sum of nodes is being considered.
Input : Binary tree: 4 / \ 2 5 / \ / \ 7 1 2 3 / 6 Output : 13 4 / \ 2 5 / \ / \ 7 1 2 3 / 6 The highlighted nodes (4, 2, 1, 6) above are part of the longest root to leaf path having sum = (4 + 2 + 1 + 6) = 13
Approach: Recursively find the length and sum of nodes of each root to leaf path and accordingly update the maximum sum.
sumOfLongRootToLeafPath(root, sum, len, maxLen, maxSum) if root == NULL if maxLen < len maxLen = len maxSum = sum else if maxLen == len && maxSum is less than sum maxSum = sum return sumOfLongRootToLeafPath(root-left, sum + root-data, len + 1, maxLen, maxSum) sumOfLongRootToLeafPath(root-right, sum + root-data, len + 1, maxLen, maxSum) sumOfLongRootToLeafPathUtil(root) if (root == NULL) return 0 Declare maxSum = Minimum Integer Declare maxLen = 0 sumOfLongRootToLeafPath(root, 0, 0, maxLen, maxSum) return maxSum
Sum = 13
Time Complexity: O(n)
This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Find maximum GCD value from root to leaf in a Binary tree
- Sum of nodes in a linked list which are greater than next node
- Update adjacent nodes if the current node is zero in a Singly Linked List
- Sum of nodes at maximum depth of a Binary Tree | Iterative Approach
- Sum of the nodes of a Singly Linked List
- Sum of all nodes in a doubly linked list divisible by a given number K
- Sum and Product of the nodes of a Singly Linked List which are divisible by K
- Sum and Product of the nodes of a Circular Singly Linked List which are divisible by K
- Find sum of even and odd nodes in a linked list
- Sum of all distinct nodes in a linked list
- Sum of smaller elements of nodes in a linked list
- Check whether the sum of element of a node is equal to the given key value
- Delete all the even nodes from a Doubly Linked List
- Delete all the nodes from a doubly linked list that are smaller than a given value
- Product of the nodes of a Singly Linked List
- Find the product of last N nodes of the given Linked List
- Print nodes of linked list at given indexes
- Print all the levels with odd and even number of nodes in it | Set-2
- Find next right node of a given key
- Find n-th node in Postorder traversal of a Binary Tree