File tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed
binary-tree-maximum-path-sum Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Time complexity: O(n)
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 answer = Number . MIN_SAFE_INTEGER ;
18
+
19
+ const dfs = ( current ) => {
20
+ const candidates = [ current . val ] ;
21
+
22
+ if ( current . left ) {
23
+ dfs ( current . left ) ;
24
+ candidates . push ( current . left . val + current . val ) ;
25
+ }
26
+
27
+ if ( current . right ) {
28
+ dfs ( current . right ) ;
29
+ candidates . push ( current . right . val + current . val ) ;
30
+ }
31
+
32
+ // 현재 노드가 루트일 경우
33
+ if ( current . left && current . right ) {
34
+ answer = Math . max (
35
+ answer ,
36
+ current . left . val + current . right . val + current . val
37
+ ) ;
38
+ }
39
+
40
+ current . val = Math . max ( ...candidates ) ;
41
+ answer = Math . max ( answer , current . val ) ;
42
+ } ;
43
+
44
+ dfs ( root ) ;
45
+
46
+ return answer ;
47
+ } ;
You can’t perform that action at this time.
0 commit comments