1 /** 2 * Definition for binary tree 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 // Start typing your C/C++ solution below 14 // DO NOT write int main() function 15 if(root==0) 16 return false; 17 if(root->left==0&&root->right==0) 18 { 19 if(root->val==sum) 20 return true; 21 return false; 22 } 23 if(root->left&&hasPathSum(root->left,sum-root->val)) 24 return true; 25 if(root->right&&hasPathSum(root->right,sum-root->val)) 26 return true; 27 return false; 28 29 } 30 }; 31 // 12ms 32 // 52ms
一定注意边界,root是否为空