题目描述
输入一颗二叉树的跟节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)
代码
class Solution {
public:
vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
if (!root)
return vector<vector<int>>();
// 先序遍历
int currentNum = 0;
vector<int> path;
vector<vector<int>> ret;
FindCore(root, expectNumber, path, currentNum, ret);
return ret;
}
void FindCore(TreeNode* root,int expectNumber,vector<int> path,
int ¤tNum, vector<vector<int> > &ret){
currentNum += root->val;
path.push_back(root->val);
bool isLeaf = !(root->left) && !(root->right);
// 和为给定值并且到了叶子节点
if (currentNum == expectNumber && isLeaf){
ret.push_back(path);
}
if (root->left!=nullptr){
FindCore(root->left, expectNumber, path, currentNum, ret);
}
if (root->right!=nullptr){
FindCore(root->right, expectNumber, path, currentNum, ret);
}
// 返回父节点前,在路径上删除当前节点
// 在currentNum中减去该节点值
path.pop_back();
currentNum -= root->val;
}
};