I was recently given a piece of code by my professor, and asked if I could find a way to reduce/eliminate as much duplicate code as possible and still have it perform the same function. The code in question is actually the code that defines the add method for Binary Search Trees:
Is there anyway to reduce/eliminate the nearly identical code for the left and right sides and still have a fully functioning add method? Keep in mind that my professor didn't specify whether its actually possible to do so, so my options are either a) show an example that works, or b) explain why there's no possible way to do it. Any help would be greatly appreciated, thanks in advance!
The given code did not compile. I have added some variables to make it compile. I think the return statements and while(true) can be replaced by using boolean variables. What other redundant code you need to remove?
Joined: May 31, 2011
And it leads to redundancy of
Ahh well no idea of doing it
Joined: Aug 27, 2011
My biggest concern was this portion of the code:
As you can see, its nearly identical to:
Is there any way to get rid of rid of this, or should I just assume that its not possible to do?
Piotr Weglarz wrote:Is there any way to get rid of rid of this, or should I just assume that its not possible to do?
Almost anything is possible in programming; the question is: is it a good idea?
In your case, I have a feeling that your prof might be trying to point you towards a recursive solution, where each branch is dealt with by calling the same method again. It's tricky but, especially for things like trees, often produces very elegant solutions.
Isn't it funny how there's always time and money enough to do it WRONG?