4 line C++ DFS solution


  • 0
    R
    /**
     * 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) return 0;
            return helper(root, sum) + pathSum(root->left, sum) + pathSum(root->right, sum);
        }
        
        int helper(TreeNode* root, int sum) {
            if(!root) return 0;
            return (sum==root->val) + helper(root->left, sum-root->val) + helper(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.