题目:
解答:
声明一个变量记录已经经过的节点的值之和,每经过一个节点就加上这个节点的值,在叶子节点判断变量值是否为目标值。
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 bool hasPathSum(TreeNode* root, int sum) 13 { 14 return helper(root, 0, sum); 15 } 16 17 bool helper(TreeNode * root, int cur, int sum) 18 { 19 if (NULL == root) 20 { 21 return false; 22 } 23 24 cur = cur + root->val; 25 26 if (root->left == NULL && root->right == NULL) 27 { 28 return cur == sum; 29 } 30 else 31 { 32 return helper(root->left, cur, sum) || helper(root->right, cur, sum); 33 } 34 } 35 };