A method meticulously crafted to traverse the tree, keeping a tally of both the length and sum of the path from the root to each leaf. By recursively exploring every possible path, it updates a global tally to reflect the maximum sum encountered on the longest path. Should multiple paths of the same length emerge, the method adeptly ensures that the path with the greatest sum is the one considered. This dual-focus approach on length and sum unveils the path that is not just the longest but also the most "valuable" in terms of node summation.
1classNode{
2constructor(val) {
3this.data = val;
4this.left = null;
5this.right = null;
6 }
7}
89const one = new Node(1);
10const two = new Node(2);
11const three = new Node(3);
12const four = new Node(4);
13const five = new Node(5);
14const six = new Node(6);
15const seven = new Node(7);
16const eight = new Node(8);
1718one.left = two;
19one.right = three;
20two.right = five;
21two.left = four;
22five.right = seven;
23five.left = six;
24seven.left = eight;
2526functionmaxHeightSum(root) {
27let maxSum = -Infinity;
28let maxLength = 0;
29if (!root) return0;
30functionsumLongestPath(root, sum, len) {
31if (!root) {
32if (maxLength < len) {
33 maxLength = len;
34 maxSum = sum;
35 } elseif (maxLength === len && maxSum < sum) {
36 maxSum = sum;
37 }
38return;
39 }
40 sumLongestPath(root.left, sum + root.data, len + 1);
41 sumLongestPath(root.right, sum + root.data, len + 1);
42 }
43 sumLongestPath(root, 0, 0);
44return maxSum;
45}
4647console.log(maxHeightSum(one));
48