首页 > 其他 > 详细

Path Sum II -- leetcode

时间:2015-05-11 09:08:15      阅读:287      评论:0      收藏:0      [点我收藏+]


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

基本思路:

深度递归。

逐层从sum中扣去当节点的val值。

到叶结点时,检查sum值是否等于该叶结点的val值。若是,则找到一个结果。


在结果集中,用最后一个元素,作为待决结果。随着栈的深入而压入元素,退出则弹出元素。


在leetcode上实际执行时间为18ms。

/**
 * 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>> ans(1);
        dfs(ans, root, sum);
        ans.pop_back();
        return ans;
    }
    
    void dfs(vector<vector<int> > &ans, TreeNode *root, int sum) {
        if (!root) return;
        if (!root->left && !root->right && root->val == sum) {
            ans.back().push_back(root->val);
            ans.push_back(ans.back());
            ans.back().pop_back();
            return;
        }
        ans.back().push_back(root->val);
        dfs(ans, root->left, sum - root->val);
        dfs(ans, root->right, sum - root->val);
        ans.back().pop_back();
    }
};


Path Sum II -- leetcode

原文:http://blog.csdn.net/elton_xiao/article/details/45622735

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!