一、问题描述
输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
二、思路
采用递归思想,如果某一路径和为目标值且当前节点是叶子节点,那么将当前路径存入所求的数组中,如果不是,递归遍历左子树和右子树,但是一定要记得如果没有符合结果的路径,一定要将当前的节点弹出。
三、代码
class Solution {
public:
vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
vector<vector<int> > res;
if(root == NULL) return res;
vector<int> path;
int currentSum = 0;
FindPath(root, expectNumber, path, currentSum, res);
return res;
}
void FindPath(TreeNode* root, int expectNumber, vector<int> path, int currentSum, vector<vector<int> >& res){
currentSum += root -> val;
path.push_back(root -> val);
bool isLeaf = root -> left == NULL && root -> right == NULL;
if(expectNumber == currentSum && isLeaf){
res.push_back(path);
}
if(root -> left != NULL) FindPath(root -> left, expectNumber, path, currentSum, res);
if(root -> right != NULL) FindPath(root -> right, expectNumber, path, currentSum, res);
path.pop_back();
}
};