16 ms C++ DFS Solution

  • 0
    class Solution {
        int pathSum(TreeNode* root, int sum) {
            if(root == NULL) return 0;
            dfs(root, sum); //start at the root, end at anywhere
            if(root->left) pathSum(root->left, sum); //nums of paths at root->left 
            if(root->right) pathSum(root->right, sum); //nums of paths at root->right 
            return result;
        int result = 0;
        void dfs(TreeNode* root, int sum) {
            if(root == NULL) return;
            if(root->val == sum) ++result;
            if(root->left) dfs(root->left, sum - root->val);
            if(root->right) dfs(root->right, sum - root->val);

Log in to reply

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