Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const hasPathToSum = function(node, targetSum) {
- if (node.length < 1) return false
- var total = 0;
- var hasPath = false
- var recurse = function(node, total){
- if (node.value){
- total += node.value;
- }
- if (total === targetSum) {
- hasPath = true;
- return
- }
- if (node.children){
- node.children.forEach(childNode => recurse(childNode, total))
- }
- }
- recurse(node, total)
- return hasPath;
- };
- // objects for testing
- var testTree = new Tree(1);
- var branch1 = testTree.addChild(2)
- var branch2 = testTree.addChild(3)
- var leaf1 = branch1.addChild(5)
- var leaf2 = branch2.addChild(6);
- var leaf3 = branch2.addChild(-2);
- var leaf4 = branch1.addChild(-5);
- var emptyTree = []
- var assertEquals = function(expected, actual, testName){
- if (actual === expected){
- console.log(`PASSED: ${testName}.`);
- } else {
- console.log(`FAILED: ${testName}. Expected ${expected}, got ${actual}.`);
- }
- }
- // tests to run on function
- assertEquals(true, hasPathToSum(testTree, 3), "It works for simple path/sum combinations")
- assertEquals(false, hasPathToSum(testTree, 21), "It works for simple path/sum combinations")
- assertEquals(true, hasPathToSum(testTree, -2), "It works for negative target sums")
- assertEquals(true, hasPathToSum(testTree, 2), "It works with negative node values")
- assertEquals(false, hasPathToSum(emptyTree, 1), "It returns false for empty trees.")
Add Comment
Please, Sign In to add comment