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