Guest User

Untitled

a guest
Jan 21st, 2018
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.74 KB | None | 0 0
  1. var pathToSum = (node, target, sum = 0, found = false) => {
  2. sum += node.value;
  3. console.log(node.value)
  4. if (sum === target) {
  5. found = true;
  6. }
  7.  
  8. if (node.left !== null && found === false) {
  9. found = pathToSum(node.left, target, sum, found);
  10. }
  11. if (node.right !== null && found === false) {
  12. found = pathToSum(node.right, target, sum, found);
  13. }
  14.  
  15. // need to find way to reverse summming when node unwinds if not found, need to assign the sum to result of recursion
  16. if (node.left === null && node.right === null && found === false) {
  17. sum -= node.value;
  18. }
  19.  
  20. return found;
  21. };
  22.  
  23. // binary tree
  24. var node1 = {
  25. value: 1,
  26. left: {
  27. value: 2,
  28. left: null,
  29. right: null
  30. },
  31. right: {
  32. value: 3,
  33. left: {
  34. value: 4,
  35. left: {value: -2, left: null, right: null},
  36. right: null
  37. },
  38. right: {
  39. value: 5,
  40. left: null,
  41. right: null
  42.  
  43. }
  44. }
  45. };
  46.  
  47. // tests
  48.  
  49. console.log('find 1', pathToSum(node1, 1)) // true - path= root:1
  50. console.log('find 2', pathToSum(node1, 2)) // false
  51. console.log('find 3', pathToSum(node1, 3)) // true - path= root:1, left:2
  52. console.log('find 4', pathToSum(node1, 4)) // true - path= root:1, right:3
  53. console.log('find 5', pathToSum(node1, 5)) // false - no path, but visits (1,2,3,4,-2,5)
  54. console.log('find 6', pathToSum(node1, 6)) // true - path= root:1, right:3, left:4, left:-2
  55. console.log('find 7', pathToSum(node1, 7)) // false - no path, but visits (1,2,3,4,-2,5)
  56. console.log('find 8', pathToSum(node1, 8)) // false - no path, but visits (1,2,3,4,-2,5)
Add Comment
Please, Sign In to add comment