124. Binary Tree Maximum Path Sum
Posted ruruozhenhao
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了124. Binary Tree Maximum Path Sum相关的知识,希望对你有一定的参考价值。
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
Approach #1: C++.
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int maxPathSum(TreeNode* root) { if (!root) return 0; int ans = INT_MIN; solve(root, ans); return ans; } private: int solve(TreeNode* root, int& ans) { if (!root) return 0; int l = max(0, solve(root->left, ans)); int r = max(0, solve(root->right, ans)); int sum = l + r + root->val; ans = max(ans, sum); return max(l, r) + root->val; } };
Approach #2: Java.
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { int ans = Integer.MIN_VALUE; public int maxPathSum(TreeNode root) { if (root == null) return 0; solve(root); return ans; } private int solve(TreeNode root) { if (root == null) return 0; int l = Math.max(0, solve(root.left)); int r = Math.max(0, solve(root.right)); int sum = l + r + root.val; ans = Math.max(ans, sum); return Math.max(l, r) + root.val; } }
Approach #3: Python.
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def solve(self, root): if not root: return 0 l = max(0, self.solve(root.left)) r = max(0, self.solve(root.right)) self.ans = max(self.ans, l + r + root.val) return max(l, r) + root.val def maxPathSum(self, root): """ :type root: TreeNode :rtype: int """ if root == None: return 0 self.ans = -sys.maxint self.solve(root) return self.ans
以上是关于124. Binary Tree Maximum Path Sum的主要内容,如果未能解决你的问题,请参考以下文章
leetcode-124. Binary Tree Maximum Path Sum
124. Binary Tree Maximum Path Sum
[leetcode-124-Binary Tree Maximum Path Sum]
leetcode -124. Binary Tree Maximum Path Sum