問你這棵樹有沒有哪條從root到leaf的路徑,是滿足路徑上的節點加總起來等於targetsum的?
呃,用Traversal,然後在找到leaf的時候,檢查此時的sum有沒有滿足,有就return true,沒有就要往上扣回到有另外一條路的部分
class Solution {
public:
bool hasPathSum(TreeNode* root, int targetSum) {
return findPath(root, targetSum, 0);
}
private:
bool findPath(TreeNode* curr, int targetSum, int currSum) {
if (curr == NULL)
return false;
if (curr->left == NULL && curr->right == NULL)
return currSum + curr->val == targetSum? true:false;
return findPath(curr->left, targetSum, currSum+curr->val) || \
findPath(curr->right, targetSum, currSum+curr->val);
}
};
只要在判斷時沒有真的加上去,就不用處理扣回來的問題
參考:
https://leetcode.com/problems/path-sum/discuss/1515918/C%2B%2B-beats-88-DFS