0

I'm working on practiceit trying to prepare for a test. I'm doing tree traversals now, an I thought I had a handle on them, but I've gotten to this question and I can't get the in order or post order traversals correct.

The question is:

Suppose that the following elements are added in the specified order to an empty binary search tree:

Meg, Stewie, Peter, Joe, Lois, Brian, Quagmire, Cleveland

Write the elements of the tree above in the order they would be seen by a pre-order, in-order, and post-order traversal. Type your solutions with the elements separated by spaces and/or commas, such as:

Its vague about how they're supposed to be added, but I assume in alphabetical order, because that's how I did the starwars one before it and that worked.

So, at least as I understand it, the tree looks like:

                            Meg
                         /      \
                      Joe         Stewie
                     /    \        /    \
                  Brian  Lois    Peter   Quagmire
                      \                   
                      Cleveland

The pre-order traversal, which it says I got right is: Meg, Joe, Brian, Cleveland, Lois, Stewie, Peter, Quagmire

However, its saying my in-order and post-order traversals are wrong and I cannot figure out why. I think the tree is right since the pre-order worked. Here's what I've got on the other two:

in-order: Brian, Cleveland, Joe, Lois, Meg, Peter, Stewie, Quagmire

post-order: Cleveland, Brian, Lois, Joe, Peter, Quagmire, Stewie, Meg

Any help would be greatly appreciated. Every time I think I've got a handle on traversals, something throws me for a loop.

EDIT: My tree is wrong. Q comes before S in the alphabet. It should be:

                            Meg
                         /      \
                      Joe         Stewie
                     /    \        /    
                  Brian  Lois    Peter   
                      \               \          
                      Cleveland         Quagmire

The correct traversals are:

pre-order : Meg, Joe, Brian, Cleveland, Lois, Stewie, Peter, Quagmire

in-order : Brian, Cleveland, Joe, Lois, Meg, Peter, Quagmire, Stewie

post-order: Cleveland, Brian, Lois, Joe, Quagmire, Peter, Stewie, Meg

insomnius1
  • 11
  • 1
  • 5

1 Answers1

0

Your tree is not correct, Quagmire should be the right child of Peter, not Stewie.

Otherwise, your traversals look good.

Henry
  • 42,982
  • 7
  • 68
  • 84