题目描述:
输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
思路:只有当所经过节点之和为所需值,并且当前节点为叶子节点时,路径为符合题意的路径。要找到所有符合题意的路径,需要遍历所有节点,只有前序遍历为先遍历根节点,
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
vector<vector<int>>res;//记录符合题意的路径
vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
if (root == nullptr) return res;
vector<int> path;//保存临时路径
int currentSum = 0;//记录临时路径上的和
FindPath(root, expectNumber, path, currentSum);
return res;
}
void FindPath(TreeNode* root, int expectedNumber, vector<int> path, int currentSum) {
currentSum += root->val;
path.push_back(root->val);
//判断是否是叶子节点
bool isLeaf = root->left == nullptr && root->right == nullptr;
if (currentSum == expectedNumber && isLeaf) {
res.push_back(path);
}
//不是叶子节点时,遍历左子树和右子树
if (root->left != nullptr)
FindPath(root->left, expectedNumber, path, currentSum);
if (root->right != nullptr)
FindPath(root->right, expectedNumber, path, currentSum);
//将当前节点出栈,返回到父节点
path.pop_back();
currentSum -= root->val;//这儿,将当前节点值减去,退回到父节点时的状态,在牛客网上,有没有都能通过……
}
};