BFS is a more intuitive solution. The disadvantage is to borrow a lot of data structure to help, perhaps can find ways to avoid.
When you need the path of the tree, it tends to re-engage a data structure, saving the parent-to-child backtracking chain, which is easy to implement.
But it does waste time and space, and one of the ways to avoid it is redundant storage. All ancestor node information is stored sequentially in each node.
Thus, when the node is selected, its ancestors are naturally determined. The number of the subject can be separated by a delimiter, such as "#", to complete the construction of the final answer.
/** * Definition for binary tree * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * Tre Enode (int x): Val (x), left (null), right (NULL) {} *}; */class Solution {public:vector<vector<int> > Pathsum (TreeNode *root, int sum) {VECTOR<VECTOR&L t;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; }};
A BFS solution that preserves all paths of a tree root to the sum of the leaves for a given value