We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent b8b8ed5 commit c243ab3Copy full SHA for c243ab3
binary-tree-maximum-path-sum/TonyKim9401.java
@@ -0,0 +1,24 @@
1
+// TC: O(n)
2
+// visit all nodes to find maximum path
3
+// SC: O(h)
4
+// h means the high of binary tree
5
+class Solution {
6
+ private int output = Integer.MIN_VALUE;
7
+ public int maxPathSum(TreeNode root) {
8
+ max(root);
9
+ return output;
10
+ }
11
+
12
+ private int max(TreeNode node) {
13
+ if (node == null) return 0;
14
15
+ int leftSum = Math.max(max(node.left), 0);
16
+ int rightSum = Math.max(max(node.right), 0);
17
18
+ int currentMax = node.val + leftSum + rightSum;
19
20
+ output = Math.max(output, currentMax);
21
22
+ return node.val + Math.max(leftSum, rightSum);
23
24
+}
0 commit comments