题解 | #二叉树中和为某一值的路径(三)#
二叉树中和为某一值的路径(三)
http://www.nowcoder.com/practice/965fef32cae14a17a8e86c76ffe3131f
比较低效率的方法:层序遍历+dfs
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
*/
class Solution {
private:
int res = 0;
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @param sum int整型
* @return int整型
*/
int FindPath(TreeNode* root, int sum) {
// write code here
if(root == nullptr){
return 0;
}
queue<TreeNode*> Q;
Q.push(root);
while(!Q.empty()){
int cur_size = Q.size();
for(int i=0; i<cur_size; i++){
auto node = Q.front();
Q.pop();
dfs(node, sum, 0);
if(node->left) Q.push(node->left);
if(node->right) Q.push(node->right);
}
}
return res;
}
void dfs(TreeNode* root, int sum, int cur_sum){
if(root == nullptr){
return;
}
cur_sum += root->val;
if(sum == cur_sum){
res += 1;
}
dfs(root->left, sum, cur_sum);
dfs(root->right, sum, cur_sum);
}
};