https://leetcode.cn/problems/binary-tree-maximum-path-sum/description/
dp, 树上搜索
因为值有负数,所以针对一个节点的更新,有四种情况:
- 节点值本身
- 节点值 + 左子树
- 节点值 + 右子树
- 节点值 + 左子树 + 右子树
要注意返回给上一层的值不能是第四种情况,因为要作为一条链返回给上层父节点
AC代码
class Solution {
public:
int ans = -0x3f3f3f3f;
int dfs(TreeNode *t)
{
if (t == nullptr)
return 0;
int lw = dfs(t->left);
int rw = dfs(t->right);
if (lw >= 0 && rw >= 0) {
ans = max(ans, lw + rw + t->val);
return max(lw, rw) + t->val;
}else if (lw >= 0 && rw <= 0)
{
ans = max(ans, lw + t->val);
return lw + t->val;
}else if (lw <= 0 && rw >= 0) {
ans = max(ans, rw + t->val);
return rw + t->val;
}
ans = max(ans, t->val);
return t->val;
}
int maxPathSum(TreeNode *root)
{
dfs(root);
return ans;
}
};
标签:rw,return,val,int,lw,124,二叉树,ans,LeetCode
From: https://www.cnblogs.com/StarTwinkle/p/16916485.html