root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8 10 / \ 5 -3 / \ \ 3 2 11 / \ \ 3 -2 1 Return 3\. The paths that sum to 8 are: 1\. 5 -> 3 2\. 5 -> 2 -> 1 3\. -3 -> 11
原题的意思是:自顶向下的找和sum的可能性的数量。
第一次考虑递归的dfs
第一个dfs,是从根节点算起。
第二个dfs,把根节点下移
class Solution {
public:
int pathSum(TreeNode* root, int sum) {
int ans=0;
dfs2(root,sum,ans);
return ans;
}
void dfs(TreeNode* root, int sum,int mysum,int &ans){
if(!root)return;
mysum+=root->val;
if(mysum==sum)++ans;
dfs(root->left,sum,mysum,ans);
dfs(root->right,sum,mysum,ans);
}
void dfs2(TreeNode* root,int sum,int &ans){
if(!root)return;
dfs(root,sum,0,ans);
dfs2(root->left,sum,ans);
dfs2(root->right,sum,ans);
}
};
如果只有一个dfs可读性变差一些了,设置了一个标记参数flag
class Solution {
public:
int pathSum(TreeNode* root, int sum) {
int ans=0;
dfs(root,sum,0,ans,0);
return ans;
}
void dfs(TreeNode* root, int sum,int mysum,int &ans,bool flag){
if(!root)return;
mysum+=root->val;
if(mysum==sum){++ans;}
dfs(root->left,sum,mysum,ans,flag);
dfs(root->right,sum,mysum,ans,flag);
if(flag)return;
dfs(root->left,sum,0,ans,1);
dfs(root->right,sum,0,ans,1);
}
};