fork download
  1. class Node:
  2.  
  3. def __init__(self, val=0, left=None, right=None):
  4. self.val = val
  5. self.left = left
  6. self.right = right
  7.  
  8.  
  9. def max_subtree_sum_binary(root):
  10. max_sum = float("-inf")
  11.  
  12. def dfs(node):
  13. nonlocal max_sum
  14. if not node:
  15. return 0
  16.  
  17. current_sum = node.val + dfs(node.left) + dfs(node.right)
  18. max_sum = max(max_sum, current_sum)
  19. return current_sum
  20.  
  21. dfs(root)
  22. return max_sum
  23.  
  24.  
  25. if __name__ == "__main__":
  26. root = Node(10)
  27. root.left = Node(5)
  28. root.right = Node(-3)
  29. root.left.left = Node(3)
  30. root.left.right = Node(2)
  31. root.right.right = Node(11)
  32.  
  33. print("Maximum Subtree Sum:", max_subtree_sum_binary(root))
Success #stdin #stdout 0.08s 14032KB
stdin
Standard input is empty
stdout
Maximum Subtree Sum: 28