Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var pathToSum = (node, target, sum = 0, found = false) => {
- sum += node.value;
- console.log(node.value)
- if (sum === target) {
- found = true;
- }
- if (node.left !== null && found === false) {
- found = pathToSum(node.left, target, sum, found);
- }
- if (node.right !== null && found === false) {
- found = pathToSum(node.right, target, sum, found);
- }
- // need to find way to reverse summming when node unwinds if not found, need to assign the sum to result of recursion
- if (node.left === null && node.right === null && found === false) {
- sum -= node.value;
- }
- return found;
- };
- // binary tree
- var node1 = {
- value: 1,
- left: {
- value: 2,
- left: null,
- right: null
- },
- right: {
- value: 3,
- left: {
- value: 4,
- left: {value: -2, left: null, right: null},
- right: null
- },
- right: {
- value: 5,
- left: null,
- right: null
- }
- }
- };
- // tests
- console.log('find 1', pathToSum(node1, 1)) // true - path= root:1
- console.log('find 2', pathToSum(node1, 2)) // false
- console.log('find 3', pathToSum(node1, 3)) // true - path= root:1, left:2
- console.log('find 4', pathToSum(node1, 4)) // true - path= root:1, right:3
- console.log('find 5', pathToSum(node1, 5)) // false - no path, but visits (1,2,3,4,-2,5)
- console.log('find 6', pathToSum(node1, 6)) // true - path= root:1, right:3, left:4, left:-2
- console.log('find 7', pathToSum(node1, 7)) // false - no path, but visits (1,2,3,4,-2,5)
- 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