i have made an binary tree, and im trying to make an postorder traversal. I have already made an preorder traversal – which i though was what i needed. But after googling traversal i found out that it was postorder i need.
My thoughts are on the traversal that first the left comes out, then the right and then the root(it is postorder right? 🙂 ).
I have tried to implement it, but it looks a bit odd the out come
public static <E> String postorder(BinaryTree<E> t, Position<E> v){
String tree = "";
if(t.hasLeft(v)){
tree += postorder(t, t.left(v));
}
tree += v.element() +", ";
if(t.hasRight(v)){
tree += postorder(t, t.right(v));
}
return tree;
}
My tree is:
45
/ \
22 77
/ \ \
11 30 90
\ / /
15 25 88
My result should be after my knowledge
15,11,25,30,22,88,90,77,45
But it is
11,15,22,25,30,45,77,88,90
Can anyone see what im doing wrong – i have tried so many things. Nothing works.
You’re calling
preorderfrom within the implementation ofpostorder.Update: now it looks like you’re doing an in-order traversal but calling it postorder.
Move this line:
to the end (right before returning).