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.

Example 1:

Input: [1,2,3]

1
/ \
2 3

Output: 6

Example 2:

Input: [-10,9,20,null,null,15,7]

-10
/ \
9 20
/ \
15 7

Output: 42

题解:

后序遍历搜索左右子树最大序列,每次更新节点的单向(左or右子树)最长路径,然后保存最大值。

class Solution {
public:
void getMaxPathSum(TreeNode *root, int &ans) {
if (root == NULL) {
return;
}
getMaxPathSum(root->left, ans);
getMaxPathSum(root->right, ans);
int leftVal = 0, rightVal = 0, fullVal = 0;
if (root->right == NULL && root->left == NULL) {
ans= max(ans, root->val);
}
else if (root->right != NULL && root->left != NULL) {
leftVal = root->val + root->left->val;
rightVal = root->val + root->right->val;
fullVal = root->val + root->right->val + root->left->val;
ans = max({ans, fullVal, leftVal, rightVal});
}
else if (root->left != NULL && root->right == NULL) {
leftVal = root->val + root->left->val;
ans = max(ans, leftVal);
}
else if (root->right != NULL && root->left == NULL) {
rightVal = root->val + root->right->val;
ans = max(ans, rightVal);
}
root->val = max({root->val, leftVal, rightVal});
}
int maxPathSum(TreeNode* root) {
if (root == NULL) {
return 0;
}
int ans = root->val;
getMaxPathSum(root, ans);
return ans;
}
};