Grokking the Coding Interview: Patterns for Coding Questions
Ask Author
Back to course home

0% completed

Vote For New Content
Test case explanation

random979

Jan 3, 2024

My code is as follows

public int counter = 0; public int countPaths(TreeNode root, int S) { if (root == null) return 0; dfs(root, S, new ArrayList<>()); return counter; } public void dfs(TreeNode root, int S, List<Integer> currentSequence) { if (root == null) return; currentSequence.add(root.val); if (root.left == null && root.right == null) { // check if any ordered subset has S int pathSum = 0; ListIterator<Integer> pathIterator = currentSequence.listIterator(currentSequence.size()); while (pathIterator.hasPrevious()) { pathSum += pathIterator.previous(); // if the sum of any sub-path is equal to 'S' we increment our path count. if (pathSum == S) { counter++; } } } else { dfs(root.left, S, currentSequence); dfs(root.right, S, currentSequence); } currentSequence.remove(currentSequence.size() - 1); }

It fails for following test case

[1,0,1,1,null,6,5]

2

It seems count expected is 2? But from the input, to me seems like the count should only be 1?

Can you provide explanation or is it a bug in the test case?

0

0

Comments
Comments
Shubham Vora
Shubham Voraa year ago

Please note that the paths can start or end at any node but all paths must follow direction from parent to child (top to bottom).

On this page