I'm fairly new to Java, arriving in the "future" from C and returning to type safety from Python. I've programmed an algorithm to return the weight of the heaviest path from the root of a binary tree to one of its leaves.
Each Node
in the tree has a weight (its data). The weight of the path is the sum of all of the Nodes weights from root to leave inclusive. This algorithm finds the heaviest.
I'm looking for your suggestions to improve this code in the following areas:
- Terminology - is there a name for this problem? have I used conventional names for things?
- Correctness - are there any bugs?
- Java conventions and idioms - can I make better use of the standard libraries?
- Runtime performance.
- Repetition - is there any way to avoid writing the field names 4 times each?
package binaryTree;
class Node {
Integer data;
Node left;
Node right;
public Node(Integer data, Node left, Node right) {
this.data = data;
this.left = left;
this.right = right;
}
public Node(Integer data) {
this(data, null, null);
}
}
public class BinaryTree {
/**
* Finds the heaviest path in the tree from the given @root Node to a leaf Node.
* @param root
* @return integer representing the sum weight of the heaviest path.
*/
public static int getHeaviestPathWeight(Node root) {
if (root == null)
return 0;
else
return root.data + Math.max(getHeaviestPathWeight(root.left), getHeaviestPathWeight(root.right));
}
}
writing the field names 4 times each
. \$\endgroup\$