每次用递归都怕栈溢出
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 private: map<int,bool> sums; 12 public: 13 bool hasPathSum(TreeNode *root, int sum) { 14 // Start typing your C/C++ solution below 15 // DO NOT write int main() function 16 if(root==NULL) 17 return false; 18 sums.clear(); 19 sums[sum] = false; 20 addSum(root,0); 21 return sums[sum]; 22 } 23 24 void addSum(TreeNode *root,int pre) 25 { 26 if(root->left==NULL && root->right==NULL) 27 { 28 sums[pre+root->val] = true; 29 } 30 if(root->left!=NULL) 31 { 32 addSum(root->left,pre+root->val); 33 } 34 if(root->right!=NULL) 35 { 36 addSum(root->right,pre+root->val); 37 } 38 } 39 };