Skip to content

Commit da93a18

Browse files
committed
feat: binary-tree-maximum-path-sum
1 parent a3e16dd commit da93a18

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/**
2+
* <a href="https://leetcode.com/problems/binary-tree-maximum-path-sum/">week11-5. binary-tree-maximum-path-sum</a>
3+
* <li>Description: Given the root of a binary tree, return the maximum path sum of any non-empty path</li>
4+
* <li>Topics: Dynamic Programming, Tree, Depth-First Search, Binary Tree</li>
5+
* <li>Time Complexity: O(N), Runtime 0ms </li>
6+
* <li>Space Complexity: O(H), Memory 44.1MB</li>
7+
*/
8+
class Solution {
9+
public int maxPathSum(TreeNode root) {
10+
dfs(root);
11+
return max;
12+
}
13+
14+
int max = Integer.MIN_VALUE;
15+
public int dfs(TreeNode head) {
16+
if (head == null) return 0;
17+
18+
int left = Math.max(0, dfs(head.left));
19+
int right = Math.max(0, dfs(head.right));
20+
21+
max = Math.max(max, head.val + left + right);
22+
23+
return head.val + Math.max(left, right);
24+
}
25+
26+
}

0 commit comments

Comments
 (0)