Count parent paths

  • 0

    Straightforward - visit each node, test all paths leading to it, count the number of paths with the correct sum.

    public int pathSum(TreeNode root, int sum)
        return recursive(new ArrayList<>(), root, sum);
    int recursive(ArrayList<Integer> path, TreeNode node, int sum)
        if(node==null) return 0;
        int count = 0;
        int s = 0;
        for(int i=path.size()-1; i>=0; i--)
            if(s==sum) count++;
        count += recursive(path, node.left, sum);
        count += recursive(path, node.right, sum);
        return count;

Log in to reply

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