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; }
版权声明:本文博客原创文章,博客,未经同意,不得转载。