给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。
说明: 叶子节点是指没有子节点的节点。
示例:
给定如下二叉树,以及目标和 sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
返回:
[
[5,4,11,2],
[5,8,4,5]
]
思路
深搜,将路径上的节点的值加入vector,如果满足sum的条件则加入result
执行用时 :12 ms, 在所有 C++ 提交中击败了99.51%的用户
内存消耗 :19.6 MB, 在所有 C++ 提交中击败了95.36%的用户
/**
* 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) {
int pos=0;
vector<int> path;
vector<vector<int> >result;
dfs(root,sum,pos,path,result);
return result;
}
private:
void dfs(TreeNode* root,int sum,int& pos,vector<int>& path,vector<vector<int> >& result){
if(root==NULL)
return ;
pos+=root->val;
path.push_back(root->val);
if(!root->left&&!root->right&&pos==sum)
result.push_back(path);
dfs(root->left,sum,pos,path,result);
dfs(root->right,sum,pos,path,result);
path.pop_back();
pos-=root->val;
}
};