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 sum = 22
and,
5 / 4 8 / / / 4 / \ / 7 2 5 1
Return
[ [5,4,11,2], [5,8,4,5]]
structTreeNode {intVal; TreeNode*Left ; TreeNode*Right ; TreeNode (intx): Val (x), left (null), right (null) {}};classSolution { Public: Vector<vector<int>> pathsum (TreeNode *root,intsum) {pathgroup.clear (); if(!root)returnPathgroup; Target=sum; Vector<int>path; Preorder (Root,0, path); returnPathgroup; } voidPreorder (treenode* node,intsum,vector<int>path) {Sum= Node->val +sum; Path.push_back (Node-val); if(node->Left ) {Preorder (node-Left,sum,path); } if(node->Right ) {Preorder (node-Right,sum,path); } if(!node->left &&!node->Right ) { if(sum==target) {pathgroup.push_back (path); } } }Private: intTarget; Vector<vector<int>>Pathgroup;};
113. Path Sum II (Tree; DFS)