Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const hasPathToSum = function(node, targetSum) {
- // your code here
- let rec = function(node, targetSum, currSum) {
- if (node.value + currSum === targetSum) {
- return true;
- }
- currSum += node.value;
- if (node.right && currSum + node.right.value <= targetSum) {
- return rec(node.right, targetSum, currSum);
- } else if (node.left) {
- return rec(node.left, targetSum, currSum);
- } else {
- return false;
- }
- }
- return rec(node, targetSum, 0);
- };
- let root = {
- value: 4,
- left: {
- value: 2,
- left: {
- value: -1
- },
- right: {
- value: 3
- }
- },
- right: {
- value: 8,
- left: {
- value: 5
- },
- right: {
- value: 9
- }
- }
- };
- hasPathToSum(root, 4);
- hasPathToSum(root, 6);
- hasPathToSum(root, 5);
- hasPathToSum(root, 12);
- hasPathToSum(root, 17);
- hasPathToSum(root, 21);
- hasPathToSum(root, 0);
- hasPathToSum(root, -10);
Add Comment
Please, Sign In to add comment