"One Day together Leetcode" #113. Path Sum II

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.