Leetcode 113. 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,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
return
[
[5,4,11,2],
[5,8,4,5]
]
输入:树,目标和
输出:从根到叶满足目标和的路径
思路
深度有限搜索,同时维护一个根到当前节点路径,并且在叶子节点处进行判断;检查是否符合目标和,如果符合则将路径添加到输出结果中。此处,如果能确定树中节点值均为正数的话,可以通过剪枝操作减少运算量。
代码
/**
* 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> > res;
vector<vector<int> > pathSum(TreeNode* root, int sum) {
if(root==NULL) return res;
vector<int> emp;
dfs(root,emp,sum);
return res;
}
void dfs(TreeNode* root, vector<int> t, int sum){
if(root->left==NULL&&root->right==NULL){
if(root->val==sum){
t.push_back(root->val);
res.push_back(t);
return;
}
}else{
t.push_back(root->val);
if(root->left!=NULL){
dfs(root->left,t,sum-root->val);
}
if(root->right!=NULL){
dfs(root->right,t,sum-root->val);
}
}
}
};