原题:
解题:
思路1就是:以根节点开始遍历找到适合路径,以根节点的左孩子节点开始遍历,然后以根节点的右孩子节点开始遍历,不断循环,也就是以每个节点为起始遍历点
代码如下:
class Solution { public: int pathSum(TreeNode* root, int sum) { if(!root) return 0; int count = getPath(root,0,sum) + pathSum(root->left,sum) + pathSum(root->right,sum); return count; } int getPath(TreeNode* node, int target, int sum) { if(!node) return 0; target += node->val; return (target == sum) + getPath(node->left, target, sum) + getPath(node->right, target, sum); } };
以下代码是论坛里看到的,思路差不多,也是递归:
class Solution { public: int pathSum(TreeNode* root, int sum) { path(root,0,sum); return total; } int total; void incrementTotal(){ this->total++; } void path(TreeNode* root,int sum, int target){ if(root != NULL){ checkpath(root,0,target); path(root->left,0,target); path(root->right,0,target); } } void checkpath(TreeNode* root,int sum,int target){ if(root == NULL){ return; } int check = sum + root->val; if(check == target){ incrementTotal(); } checkpath(root->left,check,target); checkpath(root->right,check,target); } };