# Maximum sum of longest path from the root to leaf nodes in node js

Js program for Maximum sum of longest path from the root to leaf nodes. Here more solutions.

``````/*
Node JS program for
Find the sum of longest path from root to leaf node
*/
// Binary Tree node
class TreeNode
{
constructor(data)
{
//set node value
this.data = data;
this.left = null;
this.right = null;
}
}
class BinaryTree
{
constructor()
{
this.root = null;
this.height = 0;
this.result = 0;
}
// Find the longest path sum from root to leaf nodes
findPathSum(node, sum, level)
{
if (node != null)
{
// Recursively calculating the value of
// height and sum of path.
this.findPathSum(node.left, sum + node.data, level + 1);
this.findPathSum(node.right, sum + node.data, level + 1);
// Check current node is leaf or not
if (node.left == null && node.right == null)
{
// Case When node is leaf
// Check previous calculate height is small or not
if (this.height < level)
{
// When gets a new long height
this.height = level;
this.result = sum + node.data;
}
else if (this.height == level &&
this.result < sum + node.data)
{
// When Two depth are same and new result are larger
this.result = sum + node.data;
}
}
}
}
// Function which is handling the request of
// calculating longest path sum
longestPathSum()
{
// Set default value
this.result = -Number.MAX_VALUE;
this.height = 0;
// Test
this.findPathSum(this.root, 0, 0);
console.log("Result : " + this.result);
}
}

function main()
{
// Create new tree
var tree = new BinaryTree();
/*
Construct Binary tree
-----------------------
1
/ \
/   \
/     \
2       5
/ \     / \
1   7   7   2
/     \   \
9       1  -3
/
-7
*/
// Add tree node
tree.root = new TreeNode(1);
tree.root.left = new TreeNode(2);
tree.root.left.left = new TreeNode(1);
tree.root.left.right = new TreeNode(7);
tree.root.left.right.left = new TreeNode(9);
tree.root.right = new TreeNode(5);
tree.root.right.right = new TreeNode(2);
tree.root.right.left = new TreeNode(7);
tree.root.right.left.right = new TreeNode(1);
tree.root.right.left.right.left = new TreeNode(-7);
tree.root.right.right.right = new TreeNode(-3);
tree.longestPathSum();
}
// Start program execution
main();``````

Output

``Result : 7``

## Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.