每日leetcode-124

给定一个非空二叉树,返回其最大路径和。

本题中,路径被定义为一条从树中任意节点出发,达到任意节点的序列。该路径至少包含一个节点,且不一定经过根节点。

示例 1:

输入: [1,2,3]

   1
  / \
 2   3

输出: 6
示例 2:

输入: [-10,9,20,null,null,15,7]

  -10
   /
  9  20
    /  
   15   7

输出: 42

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-maximum-path-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解答

有一些因为节点可能是负数导致的坑,在注释里面也写了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
* 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 ans = 0;

int checkPathMax(TreeNode* root) {
int leftPathMax = 0, rightPathMax = 0;
if (root->left) {
leftPathMax = max(0, checkPathMax(root->left)); // 如果从下面走更小的话就别走下面了呗……
}
if (root->right) {
rightPathMax = max(0, checkPathMax(root->right));
}
ans = max(ans, leftPathMax + root->val + rightPathMax);
return max(leftPathMax, rightPathMax) + root->val;
}

int maxPathSum(TreeNode* root) {
// 对于每个节点:
// 1. 计算当前左侧的路径和
// 2. 计算右侧的路径和
// 刚开始需要初始化一下
ans = root->val; // 注意这里应该不是0,因为让节点从根节点到根节点,所以初始化为root->val
checkPathMax(root);
return ans;
}
};

对应的两个坑的样例:

  • [-3],应该是-3
  • [1,-2,3],应该是4