C++ DFS


  • 0
    L

    class Solution {

    public:
        int num = 0;
    
    public:
        void dfs_counting(TreeNode* root, int sum){
            if(root == NULL) return;
            sum -= root->val;
            if(0 == sum) num++;
            if(root->left){
                dfs_counting(root->left, sum);
            }
            if(root->right){
                dfs_counting(root->right, sum);
            }
        }
    
    void dfs(TreeNode* root, int sum){
        if(root == NULL) return;
        dfs_counting(root, sum);
        if(root->left){
            dfs(root->left, sum);
        }
        if(root->right){
            dfs(root->right, sum);
        }
    }
    
    int pathSum(TreeNode* root, int sum) {
        dfs(root, sum);
        return num;
    }
    

    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.