One Day together Leetcode
This series of articles has all been uploaded to my github address: Zeecoder ' s GitHub
You are welcome to follow my Sina Weibo, my Sina Weibo blog
Welcome reprint, Reprint please indicate the source
(i) Title
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 / / 11 13 4 / \ / 7 2 5 1
Return
[
[5,4,11,2],
[5,8,4,5]
]
(ii) Problem solving
Topic: Given a binary tree and an integer, all the root nodes to the node value on the leaf node and equal to the path of the integer.
Compared to the previous question, "One Day together Leetcode" #112. Path Sum, where the value of all nodes on the path needs to be saved.
The idea of solving the problem is still the same, but a vector is needed to store the nodes on the path.
/** * Definition for a binary tree node. * struct TreeNode {* int val; * TreeNode *left; * TreeNode *righ T * TreeNode (int x): Val (x), left (null), right (NULL) {} *}; */classSolution { Public: vector<vector<int>>Pathsum (treenode* root,intSUM) { vector<vector<int>>Ret//used to store results if(Root==null)returnRet Dfstree (Root,sum,0Ret vector<int>(0));returnRet } ?//cur: The node value on the current path and?//ret: A collection of qualifying paths?//temp: A collection of nodes on the current path voidDfstree (treenode* root,int& Sum,intCur, vector<vector<int>>& RET, vector<int>Temp) {temp.push_back (root->val); Cur + = root->val;if(Root->left==null&&root->right==null)//Judgment is leaf node{if(cur = = sum) ret.push_back (temp);//Meet the conditions and press into the set return; }if(root->left!=null) Dfstree (root->left,sum,cur,ret,temp);//traverse the left subtree if(root->right!=null) Dfstree (root->right,sum,cur,ret,temp);//Traverse Right sub-tree}};
"One Day together Leetcode" #113. Path Sum II