I am now working on find the root-to-leaf path with the maximum sum. My approach is as:
def max_sum(root):
_max = 0
find_max(root, _max, 0)
return _max
def find_max(node, max_sum, current_sum):
if not node:
return 0
current_sum += node.value
if not node.left and not node.right:
print(current_sum, max_sum, current_sum > max_sum)
max_sum = max(max_sum, current_sum)
if node.left:
find_max(node.left, max_sum, current_sum)
if node.right:
find_max(node.right, max_sum, current_sum)
current_sum -= node.value
class TreeNode():
def __init__(self, _value):
self.value = _value
self.left, self.right, self.next = None, None, None
def main():
root = TreeNode(1)
root.left = TreeNode(7)
root.right = TreeNode(9)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
root.right.left = TreeNode(2)
root.right.right = TreeNode(7)
print(max_sum(root))
root = TreeNode(12)
root.left = TreeNode(7)
root.right = TreeNode(1)
root.left.left = TreeNode(4)
root.right.left = TreeNode(10)
root.right.right = TreeNode(5)
print(max_sum(root))
main()
with output:
12 0 True
13 0 True
12 0 True
17 0 True
0
23 0 True
23 0 True
18 0 True
0
Process finished with exit code 0
The expected output is 17 and 23.
I would like to confirm why my approach can't compare max_sum
and current_sum
? Even it returned the true in the comparison, but won't update the max_sum
. Thanks for your help.