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.
To solve this, we will follow these steps−
Define a function walk(). This will take node, 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
Let us see the following implementation to get better understanding−
Example
from collections import defaultdict 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 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))
Input
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)
Output
29