A DFS solution that saves a tree root to a leaf and all paths for a given value

Source: Internet
Author: User

This topic DFS used very not confident.

(1) The use of recursion is not bold enough to consider the details, should stand higher.

(2) After the idea is clarified, notice the change of the state value, which is the state recovery. When the depth first goes to the end, it needs to be returned, and the corresponding state should return. For example, the state data that was put in the stack/vector is going to pop up.

/** * Definition for binary tree * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * Tre Enode (int x): Val (x), left (null), right (NULL) {} *}; */class Solution {public:void dfs (vector<vector<int>> &res,vector<int> &path,treenode *        root, int sum) {if (!root) return; if (!root->left&&!root->right) {if (root->val==sum) {path.push_back (Root->val)                ;                Res.push_back (path);            Path.pop_back ();        } else return;                } sum=sum-root->val;        Path.push_back (Root->val);        DFS (res,path,root->left,sum);                Path.pop_back ();        Path.push_back (Root->val);        DFS (res,path,root->right,sum);    Path.pop_back ();        } vector<vector<int> > Pathsum (TreeNode *root, int sum) {vector<vector<int>> res;        Vector<int> path; DFS (rEs,path,root,sum);            return res; }};


A DFS solution that saves a tree root to a leaf and all paths for a given value

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.