C + + Statistics binary tree path and all paths for fixed values---"Those strange Algorithms" __web

Source: Internet
Author: User

Now, the questions are as follows:

The problem refers to the cow net "leetcode" section, that is, for the binary tree to solve its and for the fixed value of all the paths, our solution is to solve the recursive recursion, if the path and for the given fixed value, then add it, otherwise, continue to solve.
The implementation code is as follows:

Code 1:

Class Solution {public
:
    vector<vector<int> > Pathsum (TreeNode *root, int sum) {
        vector<int > v;
        Vector<vector<int> >vv;
        Pathsum (ROOT,SUM,0,V,VV);
        return vv;
    }
    Statistics each current and, compare current and fixed values, if equal, add
    void Pathsum (treenode* root,int sum,int cur,vector<int> v,vector< Vector<int> >& vv) {
        if (!root) return;
        V.push_back (root->val);
        cur+=root->val;
        if (root->left==null&&root->right==null&&sum==cur) {
            vv.push_back (v);
        }
        if (root->left) pathsum (ROOT->LEFT,SUM,CUR,V,VV);
        if (root->right) pathsum (ROOT->RIGHT,SUM,CUR,V,VV);
        V.pop_back ();
        cur-=root->val;
    }
};

Code 2:
You can reduce the parameters by setting the sum to decrease to achieve the same goal.

Class Solution {public
:
    vector<vector<int> > Pathsum (TreeNode *root, int sum) {
        vector<int > v;
        Vector<vector<int> >vv;
        Pathsum (ROOT,SUM,V,VV);
        return vv;
    }
    void Pathsum (treenode* root,int sum,vector<int> v,vector<vector<int> >&vv) {
        if (!root) return;
        V.push_back (root->val);
        if (root->left==null&&root->right==null&&sum-root->val==0) {
            vv.push_back (v);
        }
        if (root->left) pathsum (ROOT->LEFT,SUM-ROOT->VAL,V,VV);
        if (root->right) pathsum (ROOT->RIGHT,SUM-ROOT->VAL,V,VV);
        V.pop_back ();
    }

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.