Path Sum II
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
解题思路
深度优先搜索。代码如下:
/**
* 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 {
private:
void pathSum(TreeNode* root, int sum, vector<int> &path, vector<vector<int>> &result) {
if (root == NULL) return;
path.push_back(root->val);
if (root->left == NULL && root->right == NULL) {
if (root->val == sum) {
result.push_back(path);
}
}
else {
pathSum(root->left, sum - root->val, path, result);
pathSum(root->right, sum - root->val, path, result);
}
// 如果 vector<int> &path 改为 vector<int> path 则不需要这条语句
path.pop_back();
}
public:
vector<vector<int>> pathSum(TreeNode* root, int sum) {
vector<int> path;
vector<vector<int>> result;
pathSum(root, sum, path, result);
return result;
}
};