C# recursive solution


  • 0
    K
    public class Solution {
        IList<IList<int>> list = new List<IList<int>>();
        public IList<IList<int>> PathSum(TreeNode root, int sum) {
            string row = String.Empty;
            if (root!=null)
                SumPath(root,0,row,sum);
            return list;
        }
        public void SumPath(TreeNode root,int sumSoFar,string row, int sum)
        {
            row = row +"*"+ root.val;
            sumSoFar = sumSoFar + root.val;
            if (root.right == null && root.left == null && sumSoFar == sum) {
                IList<int> newrow = new List<int>();
                newrow = row.TrimStart('*').Split('*').Select(int.Parse).ToList();
                list.Add(newrow);
            }
            else {
                if (root.right != null) SumPath(root.right,sumSoFar,row,sum);
                if (root.left != null) SumPath(root.left,sumSoFar,row,sum);
            }
        }
    }
    

Log in to reply
 

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