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.
- Root to leaf path with maximum distinct nodes
- Print the longest path from root to leaf in a Binary tree
- Implementing a BST where every node stores the maximum number of nodes in the path till any leaf
- Find if there is a pair in root to a leaf path with sum equals to root's data
- Print the longest leaf to leaf path in a Binary tree
- GCD from root to leaf path in an N-ary tree
- Root to leaf path sum equal to a given number
- Check if there is a root to leaf path with given sequence
- Find all root to leaf path sum of a Binary Tree
- Root to leaf path product equal to a given number
- Shortest root to leaf path sum equal to a given number
- Find the maximum sum leaf to root path in a Binary Tree
- Print the first shortest root to leaf path in a Binary Tree
- Boundary Root to Leaf Path traversal of a Binary Tree
- Maximize count of set bits in a root to leaf path in a binary tree
- Remove nodes on root to leaf paths of length < K
- Count of Root to Leaf Paths consisting of at most M consecutive Nodes having value K
- Sum of Nodes and respective Neighbors on the path from root to a vertex V
- Print the path common to the two paths from the root to the two given nodes
- Find the path from root to the given nodes of a tree for multiple queries