Given a binary tree and a sum, find all root-to-leaf paths where each path ' s sum equals the Given sum.
For example:
Given the below binary tree and
sum = 22,
5 / 4 8 / / / 4 / \ / 7 2 5 1
Return
[ [5,4,11,2], [5,8,4,5]]
The idea of disintegration: using recursive depth-first traversal to save intermediate results.
/** Definition for binary tree * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * TreeNode (int x): Val (x), left (null), right (NULL) {} *}; */classSolution { Public: Vector<vector<int> > Pathsum (TreeNode *root,intsum) {Vector<vector<int> >result; Vector<int>Intermediate; DFS (root, sum, intermediate, result); returnresult; } voidDFS (TreeNode *root,intGap, vector<int> &Intermediate, Vector<vector<int> > &result) { if(Root = =nullptr)return; Intermediate.push_back (Root-val); if(Root->left = = nullptr && Root->right = =nullptr) { if(Gap = = root->val) result.push_back (intermediate); } dfs (Root->left, gap-root->Val, intermediate, result); DFS (Root->right, gap-root->Val, intermediate, result); Intermediate.pop_back ();//Popup Fallback}};
"Leetcode" Path Sum2