一开始觉得这样做很慢,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: int ok = false; void is(TreeNode* root, int sum){ if(root == NULL) return ; if(ok == true) return ; if(sum - root -> val == 0 && root -> left == NULL && root -> right == NULL){ ok = true; return ; } is(root -> left, sum - root -> val); is(root -> right, sum - root -> val); } bool haspathSum(TreeNode* root, int sum) { is(root, sum); return ok; }};新闻热点
疑难解答