To the first target value, a return path from the tree root to the leaves and all equal to the target value.
Classical depth-first algorithm
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: void helper(TreeNode* cur, int sum, int target, vector<int>& output, vector<vector<int>>& ret){ //a(cur) //lk("root",cur) //a(sum) //a(target) //dsp if(!cur->left && !cur->right){ if(sum==target){ ret.push_back(output); } return; } if(cur->left){ output.push_back(cur->left->val); helper(cur->left, sum+cur->left->val, target, output, ret); output.pop_back(); } if(cur->right){ output.push_back(cur->right->val); helper(cur->right, sum+cur->right->val, target, output, ret); output.pop_back(); } } vector<vector<int>> pathSum(TreeNode* root, int sum) { vector<int> output; vector<vector<int>> ret; //ahd(root) //a(ret) //a(output) if(!root) return ret; output.push_back(root->val); helper(root, root->val, sum, output, ret); return ret; } };
Running dynamic presentation http://simpledsp.com/FS/Html/lc113.html