题目描述: 给定一棵二叉树和一个定值sum,要求得到二叉树中从根节点开始到某个叶节点结束的所有路径使得路径上所有结点值的和与sum相等.
分析:
可以使用先序遍历的方法,递归的遍历整棵树。
struct TreeNode
{
int val;
struct TreeNode* left;
struct TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
void func(TreeNode *root, int sum, int cur, vector<int> &path, vector<vector<int>> &res)
{
if(root == NULL)
return ;
cur += root->val;
path.push_back(root->val);
if(cur == sum && root->left == NULL && root->right == NULL)
{
res.push_back(path);
}
if(root->left != NULL)
{
func(root->left, sum, cur, path, res);
}
if(root->right != NULL)
{
func(root->right, sum, cut, path, res);
}
path.pop_back();
}
vector<vector<int>> findPath(TreeNode *root, int sum)
{
vector<int> path;
vector<vector<int>> res;
if(root == NULL)
{
return res;
}
int cur = 0;
func(root, sum, cur, path, res);
return res;
}