Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find sum of longest sum path from root to leaf of a binary tree in Python
Suppose we have a binary tree, we have to find the sum of the longest path from the root to a leaf node. If there are two same long paths, return the path with larger sum.
So, if the input is like:
then the output will be 20.
Algorithm
To solve this, we will follow these steps:
Define a recursive function
rec()that takes the current nodeIf current node is null, return
(0, 0)representing(depth, sum)Get the maximum result from left and right subtrees
Return
(bigger[0] + 1, bigger[1] + current_node_value)From the main method, call
rec(root)and return the sum part
Implementation
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def solve(self, root):
def rec(curr):
if not curr:
return (0, 0) # (depth, sum)
left_result = rec(curr.left)
right_result = rec(curr.right)
# Choose path with greater depth, or greater sum if depths are equal
if left_result[0] > right_result[0]:
bigger = left_result
elif left_result[0] < right_result[0]:
bigger = right_result
else:
# Same depth, choose the one with larger sum
bigger = left_result if left_result[1] > right_result[1] else right_result
return (bigger[0] + 1, bigger[1] + curr.val)
return rec(root)[1]
# Test the solution
ob = Solution()
root = TreeNode(2)
root.left = TreeNode(10)
root.right = TreeNode(4)
root.right.left = TreeNode(8)
root.right.right = TreeNode(2)
root.right.left.left = TreeNode(6)
print(ob.solve(root))
The output of the above code is:
20
How It Works
The algorithm uses a recursive approach where each call returns a tuple (depth, sum):
Base case: If node is
None, return(0, 0)Recursive case: Get results from left and right subtrees
Selection: Choose the subtree with greater depth. If depths are equal, choose the one with larger sum
Return: Add 1 to depth and current node's value to sum
In our example, the longest path is 2 ? 4 ? 8 ? 6 with depth 4 and sum 20.
Conclusion
This solution efficiently finds the sum of the longest root-to-leaf path using recursion. The time complexity is O(n) where n is the number of nodes, and space complexity is O(h) where h is the height of the tree.
