// Simple node class so we can construct a binary tree to test the function
function node(val)
{
this.val = val;
this.left = null;
this.right = null;
}
var findPaths = function()
{
function traverseForSum(node, sum, pathString, v)
{
sum += node.val;
pathString += node.val + ',';
if (sum === v)
{
console.log(pathString);
}
if (node.left) traverseForSum(node.left, sum, pathString, v);
if (node.right) traverseForSum(node.right, sum, pathString, v);
}
return function(node, v)
{
traverseForSum(node, 0, '', v);
if (node.left) findPaths(node.left, v);
if (node.right) findPaths(node.right, v);
};
}();
var tree = new node(1);
tree.left = new node(5);
tree.left.left = new node(2);
tree.left.left.right = new node(4);
tree.left.left.right.right = new node(10);
tree.left.left.right.right.right = new node(3);
tree.left.left.right.right.right.right = new node(3);
tree.left.left.right.right.right.right.right = new node(1);
tree.left.left.right.right.right.right.right.right = new node(3);
tree.left.left.right.right.right.right.right.right.right = new node(3);
tree.left.left.right.right.right.right.right.right.right.right = new node(1);
tree.left.left.left = new node(10);
tree.left.left.left.right = new node(3);
tree.left.left.left.right.right = new node(4);
tree.left.left.left.left = new node(6);
tree.left.left.left.left.right = new node(1);
tree.left.left.left.left.left = new node(1);
tree.right = new node(9);
tree.right.left = new node(2);
tree.right.left.right = new node(5);
tree.right.right = new node(8);
tree.right.right.right = new node(6);
tree.right.right.right.left = new node(1);
tree.right.right.right.left.right = new node(2);
tree.right.right.right.left.right.left = new node(4);
tree.right.right.right.right = new node(3);
tree.right.right.right.right.right = new node(3);
tree.right.right.right.right.right.left = new node(1);
findPaths(tree, 7);
Output