I’m trying to write a method for the maximum sum of a path through a binary tree:
public class ConsTree<T> extends BinaryTree<T>
{
BinaryTree<T> left;
BinaryTree<T> right;
T data;
public int maxSum()
{
}
}
As is shown, each tree contains a tree to its left and to its right, as well as a data of a generic type. I am somewhat confused on how to go about starting this. If someone could provide help as to what the algorithm might look like or put me in the right direction, that would be great. Thanks.
The way to think recursively is to consider the cases. In our case, we look at a single node and can decide what paths it has:
In case 1, the maximum must be that node’s value. In case 2, the maximum is that node’s value, plus the max-path-sum of its child (since that path is extended to a path for the parent through the only child). In case 3, the maximum is the maximum max-path-sum of its two children (since the best path must go through one of the two children, and the parent can see which of the children’s best paths is better).
Therefore, the code is really simple. Here, since you return an
int, I’m going to assumeT = int.