113. Path Sum II

来源:互联网 发布:javascript入门难吗 编辑:程序博客网 时间:2024/06/04 08:05

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

这一题和112题思路是一样的,只是多了一些引用的参数,因为这一次需要保存所有等于sum的路径。所以在递归时并不是找到一条路径就返回true,而是要全部访问完才可以,代码如下。

Code(LeetCode运行13ms)

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



原创粉丝点击