Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const hasPathToSum = function (node, targetSum) {
- // your code here
- //recursive function
- //start at node (root); DFS to see whether leave reaches the sum
- //if reaches sum, return true;
- //if not, & full binary-tree traversed, return false;
- const sumChecker = (currentNode, sum) => {
- //performs a DFS
- //compares value to targetSum
- let currentSum = sum || 0;
- currentSum += currentNode.value;
- if (currentNode.children) {
- for (var i = 0; i < currentNode.children.length; i++) {
- sumChecker(currentNode.children[i], currentSum);
- }
- //once no more children (DFS - @ the leaf node), compare currentSum to targetSum
- //key point: set this condition after children-check is done, so you know you're at the leaf node
- }
- if (currentSum === targetSum) {
- return true;
- }
- }
- //run sumChecker on the node & target sum;
- //if any DFS results in target sum
- if (sumChecker(node) === true) {
- return true;
- } else {
- return false;
- }
- };
Add Comment
Please, Sign In to add comment