Given a non-empty binary tree, find the maximum path sum.

For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.

Example 1:


Input: [1,2,3]

       1
      / \
     2   3

Output: 6


Example 2:


Input: [-10,9,20,null,null,15,7]

   -10
   / \
  9  20
    /  \
   15   7

Output: 42

Difficulty: interview

Starter code:

# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
    self.val = val
    self.left = left
    self.right = right
class Solution:
    def maxPathSum(self, root: TreeNode) -> int:
        

Solutions:
# Definition for a binary tree node.
 # class TreeNode:
 #     def __init__(self, x):
 #         self.val = x
 #         self.left = None
 #         self.right = None
 
 class Solution:
 	def currentmax(self,root):
 		leftval = 0
 		if root.left != None:
 			leftval = self.currentmax(root.left)
 			leftval = 0 if leftval < 0 else leftval
 		rightval = 0
 		if root.right != None:
 			rightval = self.currentmax(root.right)
 			rightval = 0 if rightval < 0 else rightval
 		currentnode = leftval + rightval + root.val
 		if self.flag == 0:
 			self.ans = currentnode
 			self.flag = 1
 		else:
 			self.ans = self.ans if self.ans > currentnode else currentnode
 		return root.val + (leftval if leftval > rightval else rightval)
 	def maxPathSum(self, root):
 		self.ans = 0
 		self.flag = 0
 		self.currentmax(root)
 		return self.ans

# Definition for a binary tree node.
 # class TreeNode:
 #     def __init__(self, x):
 #         self.val = x
 #         self.left = None
 #         self.right = None
 import sys
 
 class Solution:
     def __init__(self):
         self.max = -sys.maxsize
         
     def maxPathSum(self, root):
         self.mps(root)
         return self.max
     
     def mps(self, root):
         # returns max path-to-leaf from ROOT
         if not root.left and not root.right: 
             self.max = max(self.max, root.val)
             return root.val
         if not root.left and root.right:
             right = self.mps(root.right)
             self.max = max(self.max, root.val, root.val + right)
             return max(root.val, root.val + right)
         if root.left and not root.right: 
             left = self.mps(root.left)
             self.max = max(self.max, root.val, root.val + left)
             return max(root.val, root.val + left)
         left = self.mps(root.left)
         right = self.mps(root.right)
         self.max = max(self.max, root.val, left + root.val, root.val + right, left + root.val + right)
         return max(root.val, left + root.val, right + root.val)