a(i):以节点i作为终点的单边最大路径和
b(i):以节点i作为终点的双边边最大路径和
a(i) = max{ i->val, i->val + max{a(i->left), a(i->right) }};
b(i) = max{ i->val, i->val + max{a(i->left), a(i->right) } , i->val + a(i->left) + a(i->right)};
由于a(i), b(i)仅仅和a(i->left)和a(i->right) 有关,因此可以将空间压缩为O(1)
代码如下:
int maxPathSum(TreeNode *root) {
int res = INT_MIN;
getSum(root, res);
return res;
}
int getSum(TreeNode * root, int & res)
{
if (root == NULL) return 0;
int l = getSum(root->left, res);
int r = getSum(root->right, res);
int a, b;
a = max(root->val, root->val + max(l, r));//one side
b = max(a, root->val + l + r); //both side
res = max(res, max(a, b));
return a;
}