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

0% completed

Vote For New Content
int count =0; HashMap hmap = new HashMap(); public int pathS...

Avinash Agarwal

Apr 6, 2022

int count =0; HashMap hmap = new HashMap();

public int pathSum(TreeNode root, int targetSum) { pathSum(root, 0, targetSum); return count; }

private void pathSum(TreeNode node, int curSum, int targetSum) { if(node == null) return;

curSum += node.val;

if(curSum == targetSum) count++;

count += hmap.getOrDefault(curSum-targetSum, 0);

hmap.put(curSum, hmap.getOrDefault(curSum, 0) + 1);

pathSum(node.left, curSum, targetSum); pathSum(node.right, curSum, targetSum);

hmap.put(curSum, hmap.get(curSum) -1); }

0

0

Comments
Comments
A
Avinash Agarwal4 years ago

This is an O(N) solution

On this page