Leetcode DFS path sumii

Source: Internet
Author: User
Path sum II Total accepted: 18489 total submissions: 68323my submissions

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



Given a binary tree and a value, find the path from the root to the leaf in the binary tree to make the total value of the node in the path
Equal to the given value
Train of Thought: DFS
Complexity: time O (n) Space O (log n)

/** * Definition for binary tree * 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<int> cur;    _pathSum(root, sum,cur);    return res;    }    private:    vector<vector<int> > res;        void _pathSum(TreeNode *root, int sum, vector<int> &path){    if(!root) return ;    path.push_back(root->val);    if(!root->left && !root->right){    if(root->val == sum) {    res.push_back(path);    }    }    _pathSum(root->left, sum - root->val, path);    _pathSum(root->right, sum - root->val, path);    path.pop_back();        }};


Leetcode DFS path sumii

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.