Code coverage report for lib/algorithms/4-binaryTrees/printSum.js

Statements: 89.29% (25 / 28)      Branches: 75% (9 / 12)      Functions: 100% (3 / 3)      Lines: 100% (24 / 24)      Ignored: none     

All files » lib/algorithms/4-binaryTrees/ » printSum.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43  1   1 1 1 1   1   1   19 9   9 1 1     8 8 8     9 9     1   8 6 6   8 6           1
//4.9 Given a binary tree and a value, print every path that sums to that number
var queue = require("../../../lib/dataStructures/queue.js");
 
var printSum = function(tree, sum, print) {
    Iif(tree === null) return false;
    Iif(!(print instanceof Function)) throw "Bad print function";
    Iif(sum < 1) return;
 
    findSum(tree.head, 0, []);
 
    function findSum(node, total, sumQueue) {
 
        if(node === null) return;
        var value = node.data;
 
        if(value > sum) {
            sumQueue = [];
            total = 0;
        }
        else {
            total = total + value;
            sumQueue.push(value);
            processQueue(total, sumQueue);
        }
 
        findSum(node.left, total, sumQueue.slice(0));
        findSum(node.right, total, sumQueue.slice(0));
    };
 
    function processQueue(total, sumQueue) {
 
        while(total > sum) {
            var fromQueue = sumQueue.shift();
            total = total - fromQueue;
        }
        if (total === sum) {
            print(sumQueue);
        }
    }
 
};
 
module.exports = printSum;