Reputation: 2000
I'm working on a recursive method...
public BinaryTree<T> TreeMirror ( BinaryTree<T> tree ) {
BinaryTree mirror = new BinaryTree();
mirror = clone(tree);
...
TreeMirror(...)
...
}
I do not wish for the method to make mirror
reference a different BinaryTree
object in each recursive step, nor to repeat the mirror = clone(tree)
statement after the first iteration. I'm wondering if it's possible to put in an if-statement check to see if an instance of mirror
has already been initialized -- in which case the mirror = new BinaryTree()
and mirror = clone(tree)
statements would be skipped.
I don't think this is possible without passing mirror
as an argument into the method or defining it in the class definition... but I want to make sure.
Any advice is much appreciated.
---------EDIT-----------
I am not allowed to change the method signature, so I cannot pass the object in in my implementation. I can create a mirror tree but only by modifying the original tree into a mirror which is something I want to try to avoid. I was attempting to create a new BinaryTree
object that is the mirror of the original tree that is passed in but really cannot figure out how to do it recursively.
Upvotes: 0
Views: 261
Reputation: 31
Uri's answer is the best.... refactor it into a private method and simply initialize the mirror then invoke the private (recrsive) method passing mirror as a parameter.
Upvotes: 0
Reputation: 3051
The mirror variable is local to the method, and will ALWAYS be unitialized in each call.
Passing mirror as an argument to the method is a very good option.
EDIT: If you can't modify the method signature, can you create a private method and call that to perform the recursion?
Upvotes: 1
Reputation: 89799
It's rare to see public recursive functions like that. A better solution might be to have the public method that creates the object, and then calls a private function which is recursive that just makes the necessary changes.
It's generally difficult to have the recursive function signature match what you want to show to your clients.
Upvotes: 2
Reputation: 5963
"I don't think this is possible without passing mirror as an argument into the method or defining it in the class definition... but I want to make sure."
Correct, that would be one way to do what you want, as mirror is not a recursion invariant.
The other way would be that your recursive algorithm clones just nodes, not entire subtrees.
Upvotes: 0