In this assignment, you implement a method to convert a tree to a string.
Your class must include the BinaryNode.java code.
Your class must have an instance variable that refers to (points to) the root of a tree, and some way(s) for your main method to build an arbitrary tree specified by the user.
Your class must provide a public String toString() method that converts the tree to a string, in the same way that folders are printed, with the root first, then the children of the node indented 4 spaces, the grandchildren indented 8 spaces, and so on. For example, consider a tree with root "hello". "hello" has two children, "foo" and "bar". "foo" has children "world", and "baz", and "bar" has children "bug" and "loop". That tree would be converted to the following string:
hello
foo
world
baz
bar
bug
loop
The above example shows what the string looks like when it is printed. As a string, it actuall looks like this:
"hello\n foo\n world\n baz\n bar\n bug\n loop\n"As many of you already know, "\n" is the newline character in Java.
Your implementation of the toString method must be recursive. The recursion may be in a helper method. Recursion is also usually the simplest way to implement this pre-order tree traversal.
You must also create a driver program that builds a tree specified by the user, then prints it as above. For example, you may use the following user interface, where the l/r indicate whether to go down the tree to the left or right before inserting, and for the last l/r, whether to insert as the left or right subtree.
Starting program, tree is empty.
enter string to add: hello
Adding new root node hello Your tree is: hello
Adding new node foo as the left
Your tree is:
hello
foo
Adding new node baz as the left right
Your tree is:
hello
foo
baz
Adding new node bar as the right
Your tree is:
hello
foo
baz
bar
Adding new node bug as the right left
Your tree is:
hello
foo
baz
bar
bug
Adding new node world as the left left
Your tree is:
hello
foo
world
baz
bar
bug
Adding new node loop as the right right
Your tree is:
hello
foo
world
baz
bar
bug
loop
Adding new node world as the right left right
Your tree is:
hello
foo
world
baz
bar
bug
fum
loop