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

LeetCode[Tree]: Path Sum II

时间:2015-02-03 23:05:29      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:leetcode   algorithm   c++   tree   递归   

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,

技术分享

return

技术分享

这个题目适合用递归来解,我的C++代码实现如下:

class Solution {
public:
    vector<vector<int> > pathSum(TreeNode *root, int sum) {
        vector<vector<int> > paths;
        vector<int> curr_path;
        if (!root) return paths;

        find(root, sum, paths, curr_path);

        return paths;
    }

private:
    void find(TreeNode *root, int sum, vector<vector<int> > &paths, vector<int> &curr_path) {
        curr_path.push_back(root->val);
        if (root->left == nullptr && root->right == nullptr)
            if (root->val == sum) paths.push_back(curr_path);
        if (root->left) {
            find(root->left, sum - root->val, paths, curr_path);
            curr_path.pop_back();
        }
        if (root->right) {
            find(root->right, sum - root->val, paths, curr_path);
            curr_path.pop_back();
        }
    }
};

时间性能如下图所示:

技术分享

LeetCode[Tree]: Path Sum II

标签:leetcode   algorithm   c++   tree   递归   

原文地址:http://blog.csdn.net/chfe007/article/details/43456267

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