题目描述
输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
代码
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
vector<vector<int>> array;
public:
vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
if (root == NULL)
return array;
std::vector<int> path;
int currentSum = 0;
array = FindPath(root,expectNumber,path,currentSum);
return array;
}
vector<vector<int> > FindPath(TreeNode *pRoot, int expectNumber, std::vector<int> &path, int currentSum){
currentSum += pRoot->val;
path.push_back(pRoot->val);
// 如果是叶结点,并且路径上结点和的值等于输入的值
// 打印出这条路径
bool isLeaf = pRoot->left == NULL && pRoot->right == NULL;
if(isLeaf && currentSum == expectNumber){
array.push_back(path);
}
// 如果不是叶结点,则遍历它的结点
if(pRoot->left != NULL){
FindPath(pRoot->left,expectNumber,path,currentSum);
}
if(pRoot->right !=NULL){
FindPath(pRoot->right,expectNumber,path,currentSum);
}
path.pop_back();
return array;
}
};