剑指offer-刷题笔记-中难题-JZ34 二叉树中和为某一值的路径(二)
版本1-递归
注意path.emplace_back(root->val)和path.push_back(root->val)的区别,如果是尾插临时对象的话,push_back()需要先构造临时对象,再将这个对象拷贝到容器的末尾,而emplace_back()则直接在容器的末尾构造对象,这样就省去了拷贝的过程
class Solution {
public:
vector<vector<int>> ret;
vector<int> path;
void dfs(TreeNode* root, int number) {
if (root == NULL) return;
path.emplace_back(root->val);
number -= root->val;
if(root->left == NULL && root->right == NULL && number == 0) {
ret.emplace_back(path);
}
dfs(root->left, number);
dfs(root->right, number);
path.pop_back();
}
vector<vector<int>> FindPath(TreeNode* root,int expectNumber) {
dfs(root, expectNumber);
return ret;
}
};
版本2-辅助队列
#include<numeric>
class Solution {
public:
vector<vector<int>> FindPath(TreeNode* root,int expectNumber) {
vector<vector<int>> ret;
if(root == NULL) return ret;
pair<vector<int>, TreeNode*> p({root->val}, root);
queue< pair<vector<int>, TreeNode*> > q;
q.push(p);
while(!q.empty()) {
pair<vector<int>, TreeNode*> cur = q.front();
q.pop();
TreeNode* node = cur.second;
if(node->left) {
vector<int> left = cur.first;
left.push_back(node->left->val);
q.push(make_pair(left, node->left));
}
if(node->right) {
vector<int> right = cur.first;
right.push_back(node->right->val);
q.push(make_pair(right, node->right));
}
if(node->left == NULL && node->right == NULL) {
vector<int> l = cur.first;
int sum = accumulate(l.begin(), l.end(), 0);
if(sum == expectNumber) ret.push_back(l);
}
}
return ret;
}
};