Guest User

Untitled

a guest
Jan 21st, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.09 KB | None | 0 0
  1. const hasPathToSum = function (node, targetSum) {
  2. // your code here
  3.  
  4. //recursive function
  5. //start at node (root); DFS to see whether leave reaches the sum
  6. //if reaches sum, return true;
  7. //if not, & full binary-tree traversed, return false;
  8.  
  9. const sumChecker = (currentNode, sum) => {
  10. //performs a DFS
  11. //compares value to targetSum
  12. let currentSum = sum || 0;
  13.  
  14. currentSum += currentNode.value;
  15.  
  16. if (currentNode.children) {
  17. for (var i = 0; i < currentNode.children.length; i++) {
  18. sumChecker(currentNode.children[i], currentSum);
  19. }
  20. //once no more children (DFS - @ the leaf node), compare currentSum to targetSum
  21. //key point: set this condition after children-check is done, so you know you're at the leaf node
  22. }
  23. if (currentSum === targetSum) {
  24. return true;
  25. }
  26. }
  27. //run sumChecker on the node & target sum;
  28. //if any DFS results in target sum
  29. if (sumChecker(node) === true) {
  30. return true;
  31. } else {
  32. return false;
  33. }
  34. };
Add Comment
Please, Sign In to add comment