给定一个非空二叉树,返回其最大路径和。
本题中,路径被定义为一条从树中任意节点出发,达到任意节点的序列。该路径至少包含一个节点,且不一定经过根节点。
示例 1:
输入: [1,2,3]
1
/
2 3
输出: 6
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
#include <algorithm>
using namespace std;
class Solution {
public:
int maxPathSum(TreeNode* root) {
auto&& result = INT_MIN;
inorder(root, result);
return result;
}
private:
static int inorder(
TreeNode* node,
int &result
)
{
if (!node)return 0;
//经过左/右子树,能够达到的最大路径。 0为不走这颗子树
const auto left = max(inorder(node->left, result),0);
const auto right = max(inorder(node->right, result), 0);
//【左右子树最大路径 + 当前节点,能否成为最大值】
result = result > left + right + node->val ? result : left + right + node->val;
//由于一个点只能走一遍,所以返回最大路径时,在当前节点基础上,只能要么选择走左子树,要么选择走右子树
return left >= right ? node->val + left : node->val + right;
}
};