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
Time: O(N)
1 # Definition for a binary tree node. 2 # class TreeNode: 3 # def __init__(self, x): 4 # self.val = x 5 # self.left = None 6 # self.right = None 7 8 class Solution: 9 def maxPathSum(self, root: TreeNode) -> int: 10 import sys 11 self.res = -sys.maxsize - 1 12 self.helper(root, self.res) 13 return self.res 14 15 def helper(self, root, res): 16 if root is None: 17 return 0 18 left = self.helper(root.left, res) 19 right = self.helper(root.right, res) 20 if left < 0: 21 left = 0 22 if right < 0: 23 right = 0 24 cur_max = root.val + left + right 25 if cur_max > self.res: 26 # resultcan choose from both children 27 self.res = cur_max 28 # return back only choose one path 29 return root.val + max(left, right)
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { int res = Integer.MIN_VALUE; public int maxPathSum(TreeNode root) { helper(root); return res; } private int helper(TreeNode root) { if (root == null) { return 0; } int left = helper(root.left); int right = helper(root.right); left = left < 0 ? 0 : left; right = right < 0 ? 0 : right; res = Math.max(res, left + right + root.val); return Math.max(left, right) + root.val; } }