/** * 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 visit(TreeNode* r, int want, int now) { if(r==NULL) return false; if(r->left==NULL && r->right==NULL) { //leaf return (now+r->val==want); } else { return visit(r->left, want, now+r->val) || visit(r->right, want, now+r->val); } } bool hasPathSum(TreeNode* root, int sum) { if(root == NULL) return false; return visit(root, sum, 0); } };