Reputation:
I'm trying to figure out how to get the max height of a ternary tree, for a school project. For binary trees using Math.max()
is easy, but I was struggling on how to do the same thing with three children. Below is what I have so far, but I'm not at a point where I can compile yet and I'm not sure if my logic is sound. Will this work? Would would putting the left/right child comparison into a temp variable be better?
private int getHeight(TernaryNode<T> node) {
int height = 0;
if (node != null) {
height = Math.max(getHeight(node.getLeftChild()), getHeight(node.getRightChild()));
height = 1 + Math.max(height, getHeight(node.getMidChild()));
}
return height;
Upvotes: 0
Views: 1232
Reputation: 26
Yes, this will work. To make it slightly more readable, you could just write -
height = 1 + Math.max(
Math.max(
getHeight(node.getLeftChild()),
getHeight(node.getMidChild())
),
getHeight(node.getRightChild())
)
There is no need for an auxiliary variable.
Upvotes: 1