路径 被定义为一条从树中任意节点出发,沿父节点-子节点连接,达到任意节点的序列。同一个节点在一条路径序列中 至多出现一次 。该路径 至少包含一个 节点,且不一定经过根节点。
路径和 是路径中各节点值的总和。
给定一个二叉树的根节点 root
,返回其 最大路径和,即所有路径上节点值之和的最大值。
示例 1:
输入:root = [1,2,3] 输出:6 解释:最优路径是 2 -> 1 -> 3 ,路径和为 2 + 1 + 3 = 6
示例 2:
输入:root = [-10,9,20,null,null,15,7] 输出:42 解释:最优路径是 15 -> 20 -> 7 ,路径和为 15 + 20 + 7 = 42
提示:
- 树中节点数目范围是
[1, 3 * 104]
-1000 <= Node.val <= 1000
注意:本题与主站 124 题相同: https://leetcode.cn/problems/binary-tree-maximum-path-sum/
思考二叉树递归问题的经典套路:
- 终止条件(何时终止递归)
- 递归处理左右子树
- 合并左右子树的计算结果
对于本题,由于要满足题目对“路径”的定义,在返回当前子树对外贡献的最大路径和时,需要取 left
,right
的最大值
# 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:
ans = -inf
def dfs(node: TreeNode) -> int:
if not node:
return 0
left = max(0, dfs(node.left))
right = max(0, dfs(node.right))
nonlocal ans
ans = max(ans, node.val + left + right)
return node.val + max(left, right)
dfs(root)
return ans
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
private int ans = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
dfs(root);
return ans;
}
private int dfs(TreeNode node) {
if (node == null) {
return 0;
}
int left = Math.max(0, dfs(node.left));
int right = Math.max(0, dfs(node.right));
ans = Math.max(ans, node.val + left + right);
return node.val + Math.max(left, right);
}
}
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func maxPathSum(root *TreeNode) int {
ans := math.MinInt32
var dfs func(*TreeNode) int
dfs = func(node *TreeNode) int {
if node == nil {
return 0
}
left := max(0, dfs(node.Left))
right := max(0, dfs(node.Right))
ans = max(ans, node.Val+left+right)
return node.Val + max(left, right)
}
dfs(root)
return ans
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int maxPathSum(TreeNode* root) {
int ans = INT_MIN;
function<int(TreeNode*)> dfs = [&](TreeNode* node) {
if (node == nullptr) {
return 0;
}
int left = max(0, dfs(node->left));
int right = max(0, dfs(node->right));
ans = max(ans, node->val + left + right);
return node->val + max(left, right);
};
dfs(root);
return ans;
}
};