leetcode Path Sum II

题目连接

https://leetcode.com/problems/path-sum-ii/ 

Path Sum II

/**
 * 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:
	typedef vector<int> vec;
	typedef vector<vec> mat;
public:
	mat pathSum(TreeNode* root, int sum) {
		ret.clear(), ans.clear();
		if (!root) return ans;
		dfs(root, 0, sum);
		return ans;
	}
private:
	vec ret;
	mat ans;
	void dfs(TreeNode *x, int cur, int sum) {
		if (!x) return;
		if (!x->left && !x->right) {
			if (sum == x->val + cur) {
				ret.push_back(x->val);
				ans.push_back(ret);
				ret.pop_back();
			}
		}
		ret.push_back(x->val);
		dfs(x->left, cur + x->val, sum);
		dfs(x->right, cur + x->val, sum);
		ret.pop_back();
	}
};
posted @ 2015-12-09 20:31  GadyPu  阅读(193)  评论(0编辑  收藏  举报