// root指向根节点,curSum记录当前路径的和,path记录当前的路径的值,max_path记录全局最大的路径,max记录全局最大的路径和。
// 在到达叶节点并且当前路径和大于max时用path更新max_path
void GetMaxSumPath(TreeNode * root,
int curSum, vector<
int> & path, vector<
int> &max_path,
int &
max)
{
curSum += root->
val;
path.push_back(root->
val);
bool isLeaf = (root->left == NULL) && (root->right ==
NULL);
if (isLeaf && curSum >
max)
{
max_path.clear();
max_path =
path;
max =
curSum;
}
if (root->left !=
NULL)
GetMaxSumPath(root->
left, curSum, path, max_path, max);
if (root->right !=
NULL)
GetMaxSumPath(root->
right, curSum, path, max_path, max);
path.pop_back();
}
参考《剑指offer》p145:二叉树中和为某一值的路径。
转载于:https://www.cnblogs.com/vincent93/p/7647965.html