输入一颗二叉树的跟节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)
思路:利用前序遍历,假设处理当前节点,首先将当前节点加入临时数组,如果当前节点是叶子节点,且节点值等于目前节点和还差的数字,那么这就是一条完整的和等于目标值的路径。如果当前节点不是叶子节点,要用当前的目标值减去当前根节点的值,作为下次递归的目标和剩下的值。然后依次递归左子树和右子树。最后切记要pop出去当前的节点值,个中原因不太好描述清楚,主要是回溯到上一个节点。
/*
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> > FindPath(TreeNode* root,int expectNumber) {
vector<vector<int>> res;
if (root == NULL) return res;
vector<int> temp;
core(root, expectNumber, temp, res);
return res;
}
void core(TreeNode* root, int neednum,
vector<int>& temp, vector<vector<int>>& res) {
if (root == NULL) return;
temp.push_back(root->val);
if (root->left == NULL && root->right == NULL &&
root->val == neednum) {
res.push_back(temp);
}
neednum -= root->val;
core(root->left, neednum, temp, res);
core(root->right, neednum, temp, res);
temp.pop_back();
}
};