Guest User

Untitled

a guest
Jan 21st, 2018
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.37 KB | None | 0 0
  1. const hasPathToSum = function(node, targetSum) {
  2. if (node.length < 1) return false
  3. var total = 0;
  4. var hasPath = false
  5.  
  6. var recurse = function(node, total){
  7. if (node.value){
  8. total += node.value;
  9. }
  10. if (total === targetSum) {
  11. hasPath = true;
  12. return
  13. }
  14.  
  15. if (node.children){
  16. node.children.forEach(childNode => recurse(childNode, total))
  17. }
  18. }
  19.  
  20. recurse(node, total)
  21. return hasPath;
  22. };
  23.  
  24.  
  25. // objects for testing
  26. var testTree = new Tree(1);
  27. var branch1 = testTree.addChild(2)
  28. var branch2 = testTree.addChild(3)
  29. var leaf1 = branch1.addChild(5)
  30. var leaf2 = branch2.addChild(6);
  31. var leaf3 = branch2.addChild(-2);
  32. var leaf4 = branch1.addChild(-5);
  33. var emptyTree = []
  34.  
  35.  
  36.  
  37. var assertEquals = function(expected, actual, testName){
  38. if (actual === expected){
  39. console.log(`PASSED: ${testName}.`);
  40. } else {
  41. console.log(`FAILED: ${testName}. Expected ${expected}, got ${actual}.`);
  42. }
  43. }
  44.  
  45. // tests to run on function
  46. assertEquals(true, hasPathToSum(testTree, 3), "It works for simple path/sum combinations")
  47. assertEquals(false, hasPathToSum(testTree, 21), "It works for simple path/sum combinations")
  48. assertEquals(true, hasPathToSum(testTree, -2), "It works for negative target sums")
  49. assertEquals(true, hasPathToSum(testTree, 2), "It works with negative node values")
  50. assertEquals(false, hasPathToSum(emptyTree, 1), "It returns false for empty trees.")
Add Comment
Please, Sign In to add comment