1,题目要求
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.
给定非空二叉树,找到最大路径总和。
对于此问题,路径定义为沿着父子连接从树中的某个起始节点到任何节点的任何节点序列。 该路径必须至少包含一个节点,并且不需要通过根节点。
2,题目思路
对于这道题,求一条树中的路径使得加和最大。
一颗树的路径,从一个开始节点出发,向上走0步或者k步,到达某一个根节点,然后再向下走0步或者k步。一旦它往下走,就不会再上升。因此,每条路径都有一个最高节点,其也是这条路径上其他所有节点的最低公共祖先。
在对这个问题的解决上,利用递归是比较方便的策略。
在递归的过程中,对于某一个节点,我们会递归地计算它的左子树和右子树的最大的路径之和,然后判断当前节点作为根节点时,路径的值是否是当前所遍历到的所有节点的最大值。
之后,我们返回这个节点作为上升或下降路径的节点的值即可。
3,代码实现
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
static const auto s = []() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
return nullptr;
}();
class Solution {
public:
int maxPathSum(TreeNode* root) {
int res = INT_MIN;
maxPathHelper(root, res);
return res;
}
private:
int maxPathHelper(TreeNode* node, int &res){
if(node == nullptr)
return 0;
int left = max(0, maxPathHelper(node->left, res));
int right= max(0, maxPathHelper(node->right,res));
res = max(res, left + right + node->val);
return max(left, right) + node->val;
}
};