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

Path Sum II

时间:2016-02-24 22:52:35      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:

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

 

 

Subscribe to see which companies asked this question

/**
 * 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:
    void _get_path(TreeNode* root, int sum, int path_sum, vector<int> path_list, vector<vector<int>> &res_list) {
        if (NULL == root) {
            return;
        }
        path_sum = path_sum + root->val;
        path_list.push_back(root->val);
        cout << path_sum << endl;
        if (root->left == NULL  && root->right == NULL && sum == path_sum) {
            res_list.push_back(path_list);
        }
        if (root->left) {
            _get_path(root->left, sum, path_sum, path_list, res_list);
        }
        if (root->right) {
            _get_path(root->right, sum, path_sum, path_list, res_list);
        }
    }
    vector<vector<int>> pathSum(TreeNode* root, int sum) {
        vector<int> path_list;
        vector<vector<int>> res_list;
        int path_sum = 0;
        _get_path(root, sum, path_sum, path_list, res_list);
        return res_list;
    }
};

 

Path Sum II

标签:

原文地址:http://www.cnblogs.com/SpeakSoftlyLove/p/5215220.html

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