who can help me? about recursion in a binary tree
use a display method to show the tree structure, such like this:
Karen
Kathy
Ashley
Tom
null
Jane
Tim
Tony
my code(in Java)is:
void display(BinaryTreeNode tempRoot) {
//String space2="";
System.out.println(tempRoot);
space2=space2+" ";
//if the current root has no child, do nothing.
if (tempRoot.leftChild==null && tempRoot.rightChild==null) {
return;
}
if (tempRoot.leftChild!=null) {
//space1=space1+" ";
System.out.print(space2);
display(tempRoot.leftChild);
}
if (tempRoot.rightChild!=null) {
//space2=space2+" ";
System.out.print(space2);
display(tempRoot.rightChild);
}
}
I really don't know how to deal with the variable space2 and let
it increase according to the grade in the recursion method.
The problem is:
1.if I delare space2 as local variable in the method, every time the method calls itself,the space2 is innitialized. so the result
like this(no indention):
Karen
Kathy
Tony
2.if I declare space2 as class variable, every time the method calls itself, the space2 is increased by 3 spaces, the indention is
not right like this:
Karen
Kathy
Tony
who can solve it, I will add the score immediatly