jykim16
8/10/2017 - 4:25 PM

Tree has path to target sum? You are given a binary tree whose nodes all have integer values (both positive and negative). Given some targ

Tree has path to target sum? You are given a binary tree whose nodes all have integer values (both positive and negative). Given some target sum (say, 14), return true if there is any path starting from the root and ending in a leaf, such that adding up all the values along the path equals the given sum. const hasPathToSum = function(node, targetSum) { // your code here };

class Tree {
  constructor(name, val) {
    this.value = val;
    this.children = [];
    this.name = name;
  }
  addChild(child) {
    this.children.push(child)
  }
}

Gram = new Tree('Gram', 10)
Mom = new Tree('Mom', 5)
Gram.addChild(Mom)
Me = new Tree('Jon', -6)
Mom.addChild(Me);
Bro = new Tree('Phil', -3);
Mom.addChild(Bro);


const hasPathToSum = function(node, targetSum) {
  var sumOfTree = (node, result) => {
    if(result === targetSum) {
      return true;
    } else {
      for(var i = 0; i < node.children.length; i++) {
        if(sumOfTree(node.children[i], result + node.children[i].value)){
          return true
        };
      }
    }
  }
  var result = sumOfTree(node, node.value);
  return result ? result : false;
};

hasPathToSum(Gram, 15) // true
hasPathToSum(Gram, 21) //false
hasPathToSum(Gram, 9) //true
hasPathToSum(Gram, 12) //true