Given a binary tree and a sum, find all root-to-leaf paths where each path‘s sum equals the given sum. For example:
Given the below binary tree and sum = 22,
5
/ 4 8
/ / 11 13 4
/ \ / 7 2 5 1
return
[ [5,4,11,2], [5,8,4,5] ]
本质是二叉树的先序遍历! 先序遍历二叉树,将每次访问的节点值相加,直到叶子节点,然后判断这条到叶子节点的路径上所有节点的值的和是否和给定值相等,相等则将这条路径所有节点的值所组成的vector加入vecRet中。 存放路径显然是一个栈,题目中要求返回vector<vector<int>>,就将路径上的节点值放入vector<int>中,递归返回父节点的时候需要将节点从vector<int>中去掉。
vector<vector<int> > pathSum(TreeNode *root, int sum) {
vector<vector<int>> vecRet;
if (root == NULL)
return vecRet;
int currentSum = 0;
vector<int> path;
pathSum (root , sum , currentSum , path , vecRet);
return vecRet;
}
void pathSum (TreeNode* root , int sum , int currentSum , vector<int> &path , vector<vector<int>> &vecRet)
{
if (root == NULL)
return ;
TreeNode* pNode = root;
path.push_back(pNode->val);
currentSum += pNode->val;
bool isLeaf = pNode->left == NULL && pNode->right == NULL;
if (isLeaf && currentSum == sum)
vecRet.push_back(path);
if (pNode->left)
pathSum (root->left , sum , currentSum , path , vecRet);
if (pNode->right)
pathSum (root->right ,sum , currentSum , path , vecRet);
currentSum -= pNode->val;
path.pop_back();
}原文:http://blog.csdn.net/u012458164/article/details/43117687