Please read the remarks about programming problems for this course.
A binary tree may be traversed in one of three standard ways:
It is not possible to deduce a binary tree's structure solely from the order of the list of elements visited during a single traversal. It is possible, however, to construct a binary tree from a preorder and an inorder traversal.
Given a binary tree node defined as
complete the following function that constructs a binary tree given iterators to both preorder and inorder traversals:
To check that your function is correct, supply the missing code in the following tandem of overloaded functions that together draw a binary tree sideways:
When executed, the following client code fragment
should produce the following output:
(Rotate your head 90 degrees counter-clockwise to see the tree as we normally would orient it.) This output corresponds to the following graphical rendering of the tree:
Hint: Notice that the draw
function performs a backwards
inorder traversal (right subtree, node, left subtree), and the
depth of the recursion controls the amount of horizontal space to the left
of the printed node.
When you have implemented and tested the two functions, place them
in a file named treetrav.cpp
. Include the expected
comments, but do not include any other code besides the two
function definitions—this is because I will
#include
your file into my test code.
You may believe that it would be a good idea to provide a function to free
up the space held by a binary tree that a
client created via your build_tree
function. The following should work
nicely:
You do not need to provide this function, as my test code takes care of it for you. You probably want to add this code to your test code.
Since it can be challenging to write both draw
and
build_tree
at the same time, I suggest writing
draw
first. You can use the following code to
test your draw
function:
If your draw
function is correct, the above code
should display the following:
Once you get draw
working you can use it to verify
that your build_tree
function is correct. (You also
can check your build_tree
function by doing preorder and
postorder traversals on the tree it returns and comparing the
result to the original
traversals.)
Submit your completed treetrav.cpp
source file to
eclass.e.southern.edu.