Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.
基本的深搜,注意一点就是必须是根到叶子节点求和,不可在非叶子节点处停。
/**
* 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> > result;
vector<int> re;
if (!root) return result;
dfs(result,re,root,sum);
return result;
}
void dfs(vector<vector<int> >&result,vector<int> &re,TreeNode *cur,int sum){
if (sum==cur->val){
if (!cur->left&&!cur->right){ //判断是否为叶子节点
re.push_back(cur->val);
result.push_back(re);
re.pop_back();
return;
}
}
if (cur->left){ //递归左孩子
re.push_back(cur->val);
dfs(result,re,cur->left,sum-cur->val);
re.pop_back();
}
if (cur->right){ //递归右孩子
re.push_back(cur->val);
dfs(result,re,cur->right,sum-cur->val);
re.pop_back();
}
}
};
原文地址:http://blog.csdn.net/monkeyduck/article/details/44962297