c++ solution


  • 0
    W
    class Solution {
    	int countCanFormSum(TreeNode* start, int sum) {
    		int c = 0;
    		if (start->val == sum) c += 1;
    		if (start->left) c += countCanFormSum(start->left, sum - start->val);
    		if (start->right) c += countCanFormSum(start->right, sum - start->val);
    		return c;
    	}
    public:
    	int pathSum(TreeNode* root, int sum) {
    		if (root == NULL) return 0;
    		int res = 0;
    		queue<TreeNode*> q;
    		q.push(root);
    		while (!q.empty()) {
    			TreeNode* n = q.front(); 
    			q.pop();
    			if (n->left) q.push(n->left);
    			if (n->right) q.push(n->right);
    			int c = countCanFormSum(n, sum);
    			if (c) res += c;
    		}
    		return res;
    	}
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.