BFS是较为直观的解法。缺点是要借用不少数据结构的帮忙,也许可以想办法避免。
在需要树的路径时,往往会重新搞一个数据结构,保存子->父的回溯链,这个容易实现。
但确实浪费了时间和空间,避免方法之一是冗余存储。每个节点中按顺序存储所有祖先节点信息。
如此, 当该节点被选中时,它的祖先自然也就确定了。本题的数字可以用一分隔符,例如“#”分割,以完成最后的答案的构造。
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int> > pathSum(TreeNode *root, int sum) {
vector<vector<int>> res;
vector<int> path;
TreeNode *tmp;
if(!root) return res;
queue<pair<TreeNode *,int>> q;
unordered_map<TreeNode*,TreeNode *> parent;
parent[root]=nullptr;
q.push(make_pair(root,root->val));
while(!q.empty()){
auto tmp=q.front(); q.pop();
auto node = tmp.first;
auto num = tmp.second;
if(!node->left&&!node->right){
if(num==sum){
while(node!=nullptr){
path.push_back(node->val);
node=parent[node];
}
reverse(path.begin(),path.end());
res.push_back(path);
path.clear();
}
continue;
}
if(node->left){
q.push(make_pair(node->left,num+node->left->val));
parent[node->left]=node;
}
if(node->right){
q.push(make_pair(node->right,num+node->right->val));
parent[node->right]=node;
}
}
return res;
}
};