简体   繁体   中英

Is it possible to perform checks on what may be an uninitialized variable?

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.

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.

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?

"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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM