Path Sum III

来源:互联网 发布:有道mac离线缓存 编辑:程序博客网 时间:2024/06/05 08:42

啊这个递归总是会加重或者少加,办法就是你写出来那个过程,就知道哪里重了哪里少加了........

/** * 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 pathSum(TreeNode* root, int sum) {        if(root==NULL)        return 0;                return pathThis(root,sum)+pathSum(root->left,sum)+pathSum(root->right,sum);    }        int pathThis(TreeNode* root,int sum){        if(root==NULL)        return 0;        int temp=0;        if(root->val==sum)        temp+=1;        return temp+pathThis(root->left,sum-root->val)+ pathThis(root->right,sum-root->val);    }    };


0 0
原创粉丝点击