Write a method treeToList that takes a Node,
the root of an ordered binary tree, and rearranges
the small and large pointers of the tree’s
nodes so that they form a circular doubly linked list with the values in
increasing order, and returns the head of the list, the node with the
smallest value. The tests keep track of the nodes in the tree they give
you and check which one you return and where each one’s pointers point
after your method is done, so the list has to be made out of those same
nodes. An empty tree (null) is an empty list, which is
also represented by null.
Your solution must be recursive, and none of your code may use a loop
of any kind: no for, no enhanced for,
no while, no do/while. You can
write as many helper methods as you like, but they can’t loop either.
It also has to be efficient: it should do a constant amount of work for each node, however big the tree is. The tests count the method calls your code makes and allow 20 for each node in the tree, which is far more than you need. A solution that, say, walks all the way down a list to find its last node will go over that limit on the big trees at the end of the tests. Those trees have 200 nodes, too many to show, so they’re described rather than written out, and if the list is wrong you’re told the first thing wrong with it.
This is the Great Tree-List Recursion Problem, by Nick Parlante, from the reading of the same name: take an ordered binary tree and rearrange its pointers to make a circular doubly linked list out of the same nodes.
Both structures are built out of Node objects, and the
starter code imports the Node class for you.
A Node holds an int value and references to two
other nodes. data() returns the value,
and small() and large() return the two nodes,
either of which may be null. You change where a node points
with setSmall(Node) and setLarge(Node). A
node’s value can’t be changed.
In an ordered binary tree, small refers to a subtree
of nodes whose values are all less than the node’s own value
and large to a subtree of nodes whose values are all greater.
Either can be null, which represents an empty tree.
In a circular doubly linked list, large plays the role
of “next” and small the role of “previous”. The list is
circular, so the large of the last node is the first node and
the small of the first node is the last node. In a list of
one node both of its pointers point back to the node itself.
In the test results a tree is written in a compact form: a leaf is just
its value, and any other node is its value followed by
its small and large subtrees in parentheses,
with . for an empty subtree. So (4 (2 1 3) 5) is
the tree from the reading. A list is shown as the value of the node you
returned as its head and then the values you see starting from the
smallest node and following large all the way around and then
following small all the way around, which for that tree
should be head: 1; large: 1 → 2 → 3 → 4 → 5 → 1; small: 1 → 5 → 4 →
3 → 2 → 1.