题目
给定一个二叉树,它的每个结点都存放着一个整数值。
找出路径和等于给定数值的路径总数。
路径不需要从根节点开始,也不需要在叶子节点结束,但是路径方向必须是向下的(只能从父节点到子节点)。
二叉树不超过1000个节点,且节点数值范围是 [-1000000,1000000] 的整数。
示例
root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8
10
/ \
5 -3
/ \ \
3 2 11
/ \ \
3 -2 1
返回 3。和等于 8 的路径有:
1. 5 -> 3
2. 5 -> 2 -> 1
3. -3 -> 11
思路
- 对于每一个节点,向左向右遍历,计算节点和,遇到满足的就赠一。
代码
/**
* 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:
int cnt = 0;
public:
int pathSum(TreeNode* root, int sum) {
queue<TreeNode*> q;
if ( root ) q.push( root );
while ( !q.empty() ) {
TreeNode* node = q.front();
q.pop();
dfs( node, node->val, sum );
if ( node->left ) q.push( node->left );
if ( node->right ) q.push( node->right );
}
return cnt;
}
void dfs( TreeNode* node, int curSum, const int& target ) {
if ( curSum == target )
++cnt;
if ( node->left )
dfs( node->left, curSum + node->left->val, target );
if ( node->right )
dfs( node->right, curSum + node->right->val, target );
return;
}
};