forked from lemonbashar/java-algo-expert
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxPathSum.java
More file actions
53 lines (42 loc) · 1.42 KB
/
MaxPathSum.java
File metadata and controls
53 lines (42 loc) · 1.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package algoexpert.hard;
/*
PROBLEM:
Find max path sum of a binary tree.
A path is collection of connected nodes where no node is connected to more than two nodes.
LOGIC:
Each node can either be
- root
- part of path
Maintain Max globalRoot
SOLUTION:
1. Recursion : time - O(n) | space - O(log n)
*/
public class MaxPathSum
{
static class BinaryTree {
public int value;
public BinaryTree left;
public BinaryTree right;
public BinaryTree(int value) {
this.value = value;
}
}
// returns { GlobalMaxAsRoot, maxInPath}
public static int [] traverse(BinaryTree node)
{
if (node == null) { return new int[] {0, 0}; }
int [] maxPathSumsLeft = traverse(node.left);
int [] maxPathSumsRight = traverse(node.right);
int maxAsRoot = node.value + maxPathSumsLeft[1] + maxPathSumsRight[1];
int maxInPath = node.value + Integer.max(maxPathSumsLeft[1], maxPathSumsRight[1]);
maxInPath = maxInPath < 0 ? 0 : maxInPath;
maxAsRoot = Integer.max( Integer.max(maxPathSumsLeft[0], maxPathSumsRight[0]), maxAsRoot);
return new int[] {maxAsRoot, maxInPath};
}
// main function
// time : O(n) | space : O(log n) - recursive stack
public static Integer maxPathSum(BinaryTree tree) {
int [] maxPathSums = traverse(tree);
return maxPathSums[0] > maxPathSums[1] ? maxPathSums[0] : maxPathSums[1];
}
}