I’m writing a mirror image method for a binary tree. The way my class works is I have an abstract class BinaryTree, with subclasses EmptyTree and ConsTree. I’m having trouble writing the method for the ConsTree. The class looks something like this:
public class ConsTree<T> extends BinaryTree<T>
{
BinaryTree<T> left;
BinaryTree<T> right;
T data;
public BinaryTree<T> mirrorImage()
{
ConsTree<T> tree = new ConsTree<T>(this.data, this.right, this.left); //In the constructor, the second parameter sets the left tree, so creates a new tree with the left and right trees swapped
if(this.left == null && this.right == null)
return tree;
if(this.left == null)
return tree + this.right.mirrorImage();
else if(right == null)
return tree + this.left.mirrorImage();
return tree + this.left.mirrorImage() + this.right.mirrorImage();
}
Obviously this doesn’t work because I can’t use a ‘+’ operator with BinaryTree objects, however this is the basic idea of what I want to accomplish. I’m just a little confused with how to combine the trees together. Any help is appreciated. Thanks.
I take it that
BinaryTreedoes not have themirrormethod.In this case, your return type should not be
BinaryTree<T>butConstTree<T>, because you will need the branches to implementmirrorImage().I find puzzling that you assign the branches to the returned tree in the constructor, before you have the mirror of the branches. The logic would be
1) Get the mirror of branch left and right
2) Create a tree with the mirror images.
You are setting some values that you will never use there.