题目描述:
输入一颗二叉树的根结点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶子结点所经过的结点形成一条路径。(注意:在返回值的list中,数组长度大的数组靠前)
解题思路:
递归先序遍历树,把结点加入路径。
若该结点是叶子结点且当前路径和等于期待和。
弹出结点,每一轮递归返回到父节点时当前路径也应该回退一个结点。
class Solution {
public:
vector<vector<int> > res;
vector<int> tmp;
vector<vector<int> > FindPath(TreeNode* root,int sum)
{
if(NULL == root)
return res;
tmp.push_back(root->val);
//此时结点的和为sum, 且为叶子结点
if((sum - root->val == 0) && root->left == NULL && root->right == NULL)
res.push_back(tmp);
FindPath(root->left, sum - root->val);
FindPath(root->right, sum - root->val);
if(! tmp.empty())
tmp.pop_back();
return res;
}
};