leetcode Path Sum

题目连接

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

Path Sum

/**
 * 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 {
public:
	bool hasPathSum(TreeNode* root, int sum) {
		return dfs(root, 0, sum);
	}
	bool dfs(TreeNode *x, int cur, int sum) {
		if (!x) return false;
		if (!x->left && !x->right) {
			if (sum == cur + x->val) return true;
		}
		if (dfs(x->left, cur + x->val, sum)) return true;
		if (dfs(x->right, cur + x->val, sum)) return true;
		return false;
	}
};
posted @ 2015-12-09 20:33  GadyPu  阅读(161)  评论(0编辑  收藏  举报