C# recursive solution


  • 0
    T

    public class Solution {
    public IList<IList<int>> ret = new List<IList<int>>();
    public IList<int> current;

    private void clone(IList<int> a, IList<int> b)
    {
        foreach(int i in a)
        {
            b.Add(i);
        }
    }
    
    private void help(TreeNode root, int sum)
    {
        if(current == null)
        {
            current = new List<int>();
        }
        current.Add(root.val);
        if(root.left == null && root.right == null && root.val == sum)
        {
            IList<int> toAdd = new List<int>();
            clone(current, toAdd);
           ret.Add(toAdd);
        }
        if(root.left != null)
        {
            help(root.left, sum-root.val);
        }
        if(root.right != null)
        {
            help(root.right, sum-root.val);
        }
        
        current.RemoveAt(current.Count-1);
    }
    
    public IList<IList<int>> PathSum(TreeNode root, int sum) {
        if(root == null)
        {
            return ret;
        }
        help(root, sum);
        return  ret;
    }
    

    }


Log in to reply
 

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