File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed
binary-tree-maximum-path-sum Expand file tree Collapse file tree 1 file changed +33
-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
+ const maxPathSum = function ( root ) {
14
+ let max = root . val ;
15
+
16
+ function getMaxSum ( node ) {
17
+ if ( ! node ) return 0 ;
18
+
19
+ const leftVal = Math . max ( getMaxSum ( node . left ) , 0 ) ;
20
+ const rightVal = Math . max ( getMaxSum ( node . right ) , 0 ) ;
21
+
22
+ max = Math . max ( node . val + leftVal + rightVal , max ) ;
23
+
24
+ return node . val + Math . max ( leftVal , rightVal ) ;
25
+ }
26
+
27
+ getMaxSum ( root ) ;
28
+
29
+ return max ;
30
+ } ;
31
+
32
+ // 시간복잡도: O(n)
33
+ // 공간복잡도: O(h) (h: 트리의 높이, 즉 재귀 스택 깊이)
You can’t perform that action at this time.
0 commit comments