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 largest sum of any path of a binary tree in Python
Suppose we have a binary tree, we have to find the largest sum of any path that goes from the root node to the leaf node.
So, if the input is like ?
Then the output will be 29 as from root, if we follow the path 5 ? 9 ? 7 ? 8 it will be 29 after addition.
Algorithm
To solve this, we will follow these steps ?
Define a function
walk(). This will take node and current sum s-
If node is null, then
max_sum := maximum of max_sum and s
return
s := s + data of node
walk(left of node, s)walk(right of node, s)From the main method do the following ?
max_sum := 0
walk(root, 0)return max_sum
Implementation
class TreeNode:
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.right = right
class Solution:
def walk(self, node, s):
if not node:
self.max_sum = max(self.max_sum, s)
return
s += node.data
self.walk(node.left, s)
self.walk(node.right, s)
def solve(self, root):
self.max_sum = 0
self.walk(root, 0)
return self.max_sum
# Create the binary tree
ob = Solution()
root = TreeNode(5)
root.left = TreeNode(1)
root.right = TreeNode(9)
root.right.left = TreeNode(7)
root.right.right = TreeNode(10)
root.right.left.left = TreeNode(6)
root.right.left.right = TreeNode(8)
print(ob.solve(root))
The output of the above code is ?
29
How It Works
The algorithm uses depth-first search (DFS) to traverse all possible root-to-leaf paths. When it reaches a leaf node (null), it compares the current path sum with the maximum sum found so far. The recursive function explores both left and right subtrees, ensuring all paths are considered.
Example Walkthrough
For the given tree, the algorithm explores these paths ?
5 ? 1 = 6
5 ? 9 ? 7 ? 6 = 27
5 ? 9 ? 7 ? 8 = 29 (maximum)
5 ? 9 ? 10 = 24
Conclusion
This solution efficiently finds the maximum root-to-leaf path sum using DFS traversal. 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 due to recursive calls.
