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]]
Hide TagsTree Depth-first Search
Idea: DFS, recursion, pay attention to the marked RED statement
/** Definition for binary tree * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * TreeNode (int x): Val (x), left (null), right (NULL) {} *}; */classSolution {Vector<vector<int> >M_res; Vector<int>M_vec; Public: voidDFS (TreeNode * root,intsum) { if(Root = =NULL)return; if(Root->left = = NULL && Root->right = =NULL) { if(Root->val = =sum) {M_vec.push_back (Root-val); M_res.push_back (M_vec); M_vec.pop_back (); } return; } M_vec.push_back (Root ->val); if(root->Left ) {DFS (Root->left, sum-root->val); } if(root->Right ) {DFS (Root->right, sum-root->val); } M_vec.pop_back (); } Vector<vector<int> > Pathsum (TreeNode *root,intsum) {m_vec.clear (); M_res.clear (); DFS (root, sum); returnM_res; }};
[Leetcode] Path Sum II