"Leetcode" 113. Path Sum II Solution and analysis based on Java and C + +

Source: Internet
Author: User

113. Path Sum II

Total Accepted: 80509  Total Submissions: 284188  Difficulty: Medium

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]]

AnalysisThe problem is the same as the basic method of "Leetcode" 112, but it is more complicated. Because the legal path requires the root node to the leaf node (root to leaf), the search algorithm we use DFS (depth first search), the search path using the middle sequence traversal (left-root-right), because the path to meet the requirements may not be unique, the search needs to pay attention to "backtracking." in combination with the examples in the topic, the following ideas are outlined:1. Using the middle sequence traversal, from the root node 5, first search the left child node, has reached the leaf node, the first legal path is: 5-4-11-7,verify the path and whether the constraint is satisfied (sum==22);2. Save the path if it is satisfied;3. Then, the current path at the end of the data popup, the remaining 5-4-11, return, equivalent to return to the root node one by one;4. Continue to search for the right child node, 2 for the leaf nodes, so the legal path is: 5-4-11-2, test whether it satisfies the constraints;5 .....
"Precautions"There are two locations to perform the current path end data popup:1. Traverse to the leaf node, form a legal path, after verifying that the path satisfies the constraints and save, pop up the end data, return, so you can go back to the nearest root node, and then continue to search the root node child nodes;2. A node of the left and right child node traversal completed, such as the root node 11 of the child nodes 7 and 2 times the completion of the calendar, must return to the previous layer, when the need to pop up the root node 11, the current search path to: 5-4; Continue the middle sequence traversal ...
"solution based on C + +"
/** * Definition for a binary tree node. * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * TreeNode (int x): Val (x), left (NULL) , right (NULL) {}}; */class solution {public:vector<vector<int>> pathsum (treenode* root, int sum) {Vector<v                Ector<int>> result;//stores the path that satisfies the requirement vector<int> cur;//the current path if (root==null) return result;    DFS (result,cur,root,sum);//depth search return result;        } void DFS (vector<vector<int>> &result,vector<int> &cur,treenode* root,int sum) {        if (root==null) return; if (root->left==null&&root->right==null)//arrive at the leaf node, form a legal path, this time again to verify the path {cur.push_back (ROOT-&G                        T;val);//The leaf node is included in the current path if (Sumofpath (cur) ==sum)//Verify that the path satisfies the constraint result.push_back (cur);        Cur.pop_back ();//pops up the current path end data and returns return; } else {Cur.push_back (root->val);//Framework DFS (result,cur,root->left,sum) for sequential traversal;            DFS (result,cur,root->right,sum);    Cur.pop_back ();//The child node of a node is searched, end data pops up, return to the previous layer}} int Sumofpath (vector<int> &dataset)//Fetch path and        {int sum=0;        for (int i=0;i<dataset.size (); i++) {sum+=dataset[i];    } return sum; }};
Operation Result:

"Java-based solution" for a detailed knowledge of the Java solution, see my other blog post.
/** * Definition for a binary tree node.  * public class TreeNode {* int val, * TreeNode left, * TreeNode right; * TreeNode (int x) {val = x;} *} */public class Solution {public list<list<integer>> pathsum (TreeNode root, int sum) {list<l Ist<integer>> result=new arraylist<list<integer>> (); ArrayList class object Instantiation list< for//list interface variable      Integer> temp=new arraylist<integer> ();   if (root==null) return result;   DFS (result,temp,root,sum);    return result; } void DFS (list<list<integer>> result,list<integer> temp,treenode root,int sum) {if (root==n   ULL) return;   if (root.left==null&&root.right==null) {temp.add (root.val);   if (Sumofpath (temp) ==sum) Result.add (new ArrayList (temp));//must pay attention to Temp.remove (Temp.size ()-1);   Return   } else {temp.add (root.val);   DFS (result,temp,root.left,sum);   DFS (result,temp,root.right,sum);   Temp.remove (Temp.size ()-1); }} int SuMofpath (list<integer> temp) {int sum=0;   for (int i=0;i<temp.size (); i++) {sum+=temp.get (i);   } return sum; }}

Operation Result:











"Leetcode" 113. Path Sum II Solution and analysis based on Java and C + +

Related Article

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.