码迷,mamicode.com
首页 > 其他好文 > 详细

113 Path Sum II 路径总和 II

时间:2018-04-05 01:33:23      阅读:558      评论:0      收藏:0      [点我收藏+]

标签:public   ret   tco   log   ack   val   nod   str   script   

给定一个二叉树和一个和,找到所有从根到叶路径总和等于给定总和的路径。
例如,
给定下面的二叉树和 sum = 22,
              5
             / \
            4   8
           /   / \
          11  13  4
         /  \    / \
        7    2  5   1
返回
[
   [5,4,11,2],
   [5,8,4,5]
]

详见:https://leetcode.com/problems/path-sum-ii/description/

/**
 * 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<vector<int>> res;
        vector<int> path;
        if(root==nullptr)
        {
            return res;
        }
        findPath(root,sum,path,res);
        return res;
    }
    void findPath(TreeNode* root,int sum,vector<int> &path,vector<vector<int>> &res)
    {
        if(root==nullptr)
        {
            return;
        }
        path.push_back(root->val);
        if(root->val==sum&&root->left==nullptr&&root->right==nullptr)
        {
            res.push_back(path);
            path.pop_back();
        }
        else
        {
            findPath(root->left,sum-root->val,path,res);
            findPath(root->right,sum-root->val,path,res);
            path.pop_back();
        }
    }
};

 

113 Path Sum II 路径总和 II

标签:public   ret   tco   log   ack   val   nod   str   script   

原文地址:https://www.cnblogs.com/xidian2014/p/8719583.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!