C# - Recursive


  • 1
    public int PathSum(TreeNode root, int sum) {
        return PathSum(root, sum, true);
    }
    
    public int PathSum(TreeNode root, int sum, bool start) {
        int res = 0;
        if (root != null)
        {
            if (start)
            {
                res = PathSum(root.left, sum, true) + PathSum(root.right, sum, true);
            }
            
            if (root.val == sum)
            {
                res++;
            }
            
            res += PathSum(root.left, sum - root.val, false) + PathSum(root.right, sum - root.val, false);
            
        }
        return res;
    }

Log in to reply
 

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