File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed
binary-tree-maximum-path-sum Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * https://leetcode.com/problems/binary-tree-maximum-path-sum/
3
+ * Definition for a binary tree node.
4
+ * function TreeNode(val, left, right) {
5
+ * this.val = (val===undefined ? 0 : val)
6
+ * this.left = (left===undefined ? null : left)
7
+ * this.right = (right===undefined ? null : right)
8
+ * }
9
+ */
10
+ /**
11
+ * @param {TreeNode } root
12
+ * @return {number }
13
+ */
14
+ var maxPathSum = function ( root ) {
15
+ let maxSum = - Infinity ; // global max
16
+
17
+ function dfs ( node ) {
18
+ if ( ! node ) return 0 ;
19
+
20
+ // ์ผ์ชฝ๊ณผ ์ค๋ฅธ์ชฝ ์๋ธํธ๋ฆฌ์์ ์ต๋ ๊ฒฝ๋ก ํฉ์ ๊ตฌํ๋ค
21
+ // ์์๋ฉด 0์ผ๋ก ์นํ (ํด๋น ์๋ธํธ๋ฆฌ๋ฅผ ํฌํจํ์ง ์๋๊ฒ ๋ ์ด๋์ธ ๊ฒฝ์ฐ)
22
+ let leftMax = Math . max ( 0 , dfs ( node . left ) ) ;
23
+ let rightMax = Math . max ( 0 , dfs ( node . right ) ) ;
24
+
25
+ // ํ์ฌ ๋
ธ๋๋ฅผ ๋ฃจํธ๋ก ํ๋ ๊ฒฝ๋ก์์ ์ต๋๊ฐ์ ๊ณ์ฐ (left + node + right)
26
+ let currentMax = leftMax + node . val + rightMax ;
27
+
28
+ // global ์ต๋๊ฐ ๊ฐฑ์
29
+ maxSum = Math . max ( maxSum , currentMax ) ;
30
+
31
+ // ๋ถ๋ชจ ๋
ธ๋๋ก return ์: ํ์ชฝ ๋ฐฉํฅ์ผ๋ก๋ง ์ ํ ๊ฐ๋ฅ
32
+ return node . val + Math . max ( leftMax , rightMax ) ;
33
+ }
34
+
35
+ dfs ( root ) ;
36
+ return maxSum ;
37
+ } ;
You canโt perform that action at this time.
0 commit comments