Path Sum II

来源:互联网 发布:获取json的key和value 编辑:程序博客网 时间:2024/06/05 11:24

没什么要说的。注意父节点在左右子树返回时可能被计算两次。

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

http://oj.leetcode.com/problems/path-sum-ii/

0 0
原创粉丝点击