113. Path Sum II (Tree; DFS)

Source: Internet
Author: User

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 sum = 22 and,

              5             /             4   8           /   /           /  4         /  \    /         7 2 5   1

Return

[   [5,4,11,2],   [5,8,4,5]]

structTreeNode {intVal; TreeNode*Left ; TreeNode*Right ; TreeNode (intx): Val (x), left (null), right (null) {}};classSolution { Public: Vector<vector<int>> pathsum (TreeNode *root,intsum)        {pathgroup.clear (); if(!root)returnPathgroup; Target=sum; Vector<int>path; Preorder (Root,0, path); returnPathgroup; }    voidPreorder (treenode* node,intsum,vector<int>path) {Sum= Node->val +sum; Path.push_back (Node-val); if(node->Left ) {Preorder (node-Left,sum,path); }               if(node->Right ) {Preorder (node-Right,sum,path); }                if(!node->left &&!node->Right ) {            if(sum==target)            {pathgroup.push_back (path); }                }    }Private:    intTarget; Vector<vector<int>>Pathgroup;};

113. Path Sum II (Tree; DFS)

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.