File tree Expand file tree Collapse file tree 2 files changed +42
-0
lines changed Expand file tree Collapse file tree 2 files changed +42
-0
lines changed Original file line number Diff line number Diff line change 127
127
119|[ Pascal's Triangle II] ( ./0119-pascals-triangle-ii.js ) |Easy|
128
128
120|[ Triangle] ( ./0120-triangle.js ) |Medium|
129
129
121|[ Best Time to Buy and Sell Stock] ( ./0121-best-time-to-buy-and-sell-stock.js ) |Easy|
130
+ 124|[ Binary Tree Maximum Path Sum] ( ./0124-binary-tree-maximum-path-sum.js ) |Hard|
130
131
125|[ Valid Palindrome] ( ./0125-valid-palindrome.js ) |Easy|
131
132
128|[ Longest Consecutive Sequence] ( ./0128-longest-consecutive-sequence.js ) |Medium|
132
133
131|[ Palindrome Partitioning] ( ./0131-palindrome-partitioning.js ) |Medium|
Original file line number Diff line number Diff line change
1
+ /**
2
+ * 124. Binary Tree Maximum Path Sum
3
+ * https://leetcode.com/problems/binary-tree-maximum-path-sum/
4
+ * Difficulty: Hard
5
+ *
6
+ * A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the
7
+ * sequence has an edge connecting them. A node can only appear in the sequence at most
8
+ * once. Note that the path does not need to pass through the root.
9
+ *
10
+ * The path sum of a path is the sum of the node's values in the path.
11
+ *
12
+ * Given the root of a binary tree, return the maximum path sum of any non-empty path.
13
+ */
14
+
15
+ /**
16
+ * Definition for a binary tree node.
17
+ * function TreeNode(val, left, right) {
18
+ * this.val = (val===undefined ? 0 : val)
19
+ * this.left = (left===undefined ? null : left)
20
+ * this.right = (right===undefined ? null : right)
21
+ * }
22
+ */
23
+ /**
24
+ * @param {TreeNode } root
25
+ * @return {number }
26
+ */
27
+ var maxPathSum = function ( root ) {
28
+ let result = - Infinity ;
29
+
30
+ function traverse ( node ) {
31
+ if ( ! node ) return 0 ;
32
+ const leftValue = Math . max ( traverse ( node . left ) , 0 ) ;
33
+ const rightValue = Math . max ( traverse ( node . right ) , 0 ) ;
34
+ result = Math . max ( result , node . val + leftValue + rightValue ) ;
35
+ return node . val + Math . max ( leftValue , rightValue ) ;
36
+ }
37
+
38
+ traverse ( root ) ;
39
+
40
+ return result ;
41
+ } ;
You can’t perform that action at this time.
0 commit comments