File tree 1 file changed +37
-0
lines changed
binary-tree-maximum-path-sum
1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change
1
+ // ✅ Time Complexity: O(N) (Each node is visited once)
2
+ // ✅ Space Complexity: O(N)
3
+
4
+ /**
5
+ * Definition for a binary tree node.
6
+ * function TreeNode(val, left, right) {
7
+ * this.val = (val===undefined ? 0 : val)
8
+ * this.left = (left===undefined ? null : left)
9
+ * this.right = (right===undefined ? null : right)
10
+ * }
11
+ */
12
+ /**
13
+ * @param {TreeNode } root
14
+ * @return {number }
15
+ */
16
+ var maxPathSum = function ( root ) {
17
+ let maxSum = - Infinity ;
18
+
19
+ const dfs = ( node ) => {
20
+ if ( ! node ) return 0 ;
21
+
22
+ let leftMax = Math . max ( dfs ( node . left ) , 0 ) ;
23
+ let rightMax = Math . max ( dfs ( node . right ) , 0 ) ;
24
+
25
+ // Compute best path sum that passes through this node
26
+ let currentMax = node . val + leftMax + rightMax ;
27
+
28
+ // Update global maxSum
29
+ maxSum = Math . max ( maxSum , currentMax ) ; // represents the best path sum for the current node.
30
+
31
+ return node . val + Math . max ( leftMax , rightMax ) ; // propagates the maximum path sum to the parent node.
32
+ } ;
33
+
34
+ dfs ( root ) ;
35
+ return maxSum ;
36
+ } ;
37
+
You can’t perform that action at this time.
0 commit comments