File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed
binary-tree-maximum-path-sum Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change 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+
You can’t perform that action at this time.
0 commit comments