Skip to content

Commit 5262708

Browse files
authored
add binary tree maximum path sum
1 parent f63ad48 commit 5262708

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* public class TreeNode {
4+
* int val;
5+
* TreeNode left;
6+
* TreeNode right;
7+
* TreeNode() {}
8+
* TreeNode(int val) { this.val = val; }
9+
* TreeNode(int val, TreeNode left, TreeNode right) {
10+
* this.val = val;
11+
* this.left = left;
12+
* this.right = right;
13+
* }
14+
* }
15+
*/
16+
class Solution {
17+
18+
// 최대 Path 누적 합
19+
int maxPathSumVal = Integer.MIN_VALUE;
20+
21+
// 시간복잡도: O(n), 공간복잡도: O(h) h as height of tree
22+
public int maxPathSum(TreeNode root) {
23+
maxPathSumChecker(root);
24+
return maxPathSumVal;
25+
}
26+
27+
// 재귀
28+
private int maxPathSumChecker(TreeNode node) {
29+
30+
if (node == null) {
31+
return 0;
32+
}
33+
34+
int leftMax = Math.max(maxPathSumChecker(node.left), 0);
35+
int rightMax = Math.max(maxPathSumChecker(node.right), 0);
36+
37+
maxPathSumVal = Math.max(node.val + leftMax + rightMax, maxPathSumVal);
38+
39+
return node.val + Math.max(leftMax, rightMax);
40+
}
41+
}
42+

0 commit comments

Comments
 (0)