Skip to content

Commit bfe0319

Browse files
committed
add Binary Tree Maximum Path Sum solution
1 parent 3092dfb commit bfe0319

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* [Problem]: [124 Binary Tree Maximum Path Sum
3+
* (https://leetcode.com/problems/binary-tree-maximum-path-sum/description/)
4+
*/
5+
/**
6+
* Definition for a binary tree node.
7+
* class TreeNode {
8+
* val: number
9+
* left: TreeNode | null
10+
* right: TreeNode | null
11+
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
12+
* this.val = (val===undefined ? 0 : val)
13+
* this.left = (left===undefined ? null : left)
14+
* this.right = (right===undefined ? null : right)
15+
* }
16+
* }
17+
*/
18+
19+
//시간복잡도 O(n)
20+
//공간복잡도 O(h)
21+
function maxPathSum(root: TreeNode | null): number {
22+
if (!root) return 0;
23+
let result = root.val;
24+
25+
function dfs(node: TreeNode | null) {
26+
if (!node) return 0;
27+
28+
let leftMax = Math.max(dfs(node.left), 0);
29+
let rightMax = Math.max(dfs(node.right), 0);
30+
31+
result = Math.max(node.val + leftMax + rightMax, result);
32+
33+
return node.val + Math.max(leftMax, rightMax);
34+
}
35+
36+
dfs(root);
37+
return result;
38+
}

0 commit comments

Comments
 (0)