Guest User

Untitled

a guest
Jan 21st, 2018
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.82 KB | None | 0 0
  1. const hasPathToSum = function(node, targetSum) {
  2. // your code here
  3. let rec = function(node, targetSum, currSum) {
  4. if (node.value + currSum === targetSum) {
  5. return true;
  6. }
  7. currSum += node.value;
  8. if (node.right && currSum + node.right.value <= targetSum) {
  9. return rec(node.right, targetSum, currSum);
  10. } else if (node.left) {
  11. return rec(node.left, targetSum, currSum);
  12. } else {
  13. return false;
  14. }
  15. }
  16. return rec(node, targetSum, 0);
  17. };
  18.  
  19. let root = {
  20. value: 4,
  21. left: {
  22. value: 2,
  23. left: {
  24. value: -1
  25. },
  26. right: {
  27. value: 3
  28. }
  29. },
  30. right: {
  31. value: 8,
  32. left: {
  33. value: 5
  34. },
  35. right: {
  36. value: 9
  37. }
  38. }
  39. };
  40.  
  41. hasPathToSum(root, 4);
  42. hasPathToSum(root, 6);
  43. hasPathToSum(root, 5);
  44. hasPathToSum(root, 12);
  45. hasPathToSum(root, 17);
  46. hasPathToSum(root, 21);
  47. hasPathToSum(root, 0);
  48. hasPathToSum(root, -10);
Add Comment
Please, Sign In to add comment