I am working on one question, Find max path sum from two leaves

Given a binary tree in which each node element contains a number. Find the maximum possible sum from one leaf node to another.

class TreeNode:
    def __init__(self, x=None):
        self.val = x
        self.left = None
        self.right = None

def maxPathSum(root: TreeNode) -> int:
    res = float('-inf')

    def traversal(node, pathsum):
        nonlocal res

        if node is None:
            return 0
        if node.left is None and node.right is None:
            return node.val
        ln_value = traversal(node.left, pathsum)
        rn_value = traversal(node.right, pathsum)
        if node.left is not None and node.right is not None:
            res = max(res, node.val + ln_value + rn_value)
            return max(ln_value, rn_value) + node.val

        if node.left is None:
            return rn_value + node.val
            return ln_value + node.val

    traversal(root, res)
    return res

closed as off-topic by Austin Hastings, esote, pacmaninbw, яүυк, Heslacher Apr 25 at 9:28

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Code not implemented or not working as intended: Code Review is a community where programmers peer-review your working code to address issues such as security, maintainability, performance, and scalability. We require that the code be working correctly, to the best of the author's knowledge, before proceeding with a review." – Austin Hastings, esote, pacmaninbw, яүυк, Heslacher
If this question can be reworded to fit the rules in the help center, please edit the question.

  • \$\begingroup\$ This code won't work on the example given behind your link. (Or any example with a half-full node.) Perhaps you should debug it more before asking for a review. \$\endgroup\$ – Austin Hastings Apr 21 at 20:00
  • \$\begingroup\$ my bad post the wrong code. updated already. any good idea how to handle to res if not using nonlocal? \$\endgroup\$ – A.Lee Apr 21 at 21:10
  • \$\begingroup\$ Return a tuple. And it still doesn't work, I think. What if your tree is (10, (-1), (-1))? \$\endgroup\$ – Austin Hastings Apr 21 at 22:54
  • \$\begingroup\$ what do you mean return a tuple? \$\endgroup\$ – A.Lee Apr 22 at 19:47
  • \$\begingroup\$ A tuple is a built-in Python type. There is syntactic sugar for constructing them, so you can do something like: return (1, 2) \$\endgroup\$ – Austin Hastings Apr 22 at 19:49

Browse other questions tagged or ask your own question.