# leetcode中的112. 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) {
int res = 0;
return __hasPathSum(root, sum, res);
}

bool __hasPathSum(TreeNode* root, int sum, int &res) {

if ((res == sum) && (root->left == NULL) && (root->right == NULL)) {
return true;
}

if (root == NULL) {
return false;
}

res += root->val;

return __hasPathSum(root->left, sum, res) || __hasPathSum(root->right, sum, res);
}
};``````

``````[1,-2,-3,1,3,-2,null,-1]
-3``````

2 个回答

``````/**
* 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 __hasPathSum(root, sum, 0);
}

bool __hasPathSum(TreeNode* root, int sum, int res) {

if (root == NULL) {
return false;
}

if ((res + root->val == sum) && (root->left == NULL) && (root->right == NULL)) {
return true;
}

return __hasPathSum(root->left, sum, res+root->val) || __hasPathSum(root->right, sum, res+root->val);
}
};``````

c++执行结果：
Runtime Error Message:
Line 20: member access within null pointer of type 'struct TreeNode'
Last executed input:
[]
0

###### 你尚未登录，登录后可以
• 和开发者交流问题的细节
• 关注并接收问题和回答的更新提醒
• 参与内容的编辑和改进，让解决方法与时俱进