Since you've tagged it as homework, I'll reply without source code or pseudo code, but with a more all-round description.
Since your tree will contain all the values you want to contain in the linked list, we have to make sure we reach them all.
To do that, we'll have to make sure we process every leaf node.
To do that, we need to make sure we process every left and right child of every node.
Let's start with the root node, which is generally the one you have a reference to when you're talking about a binary tree.
I'm assuming you know how to produce a linked list by sequentially appending items to it.
So to process the root node, we do this:
- If the root contains a value: Append the value to the list
That takes care of the single value that can optionally be stored in the root node. Some binary trees only store values in leaf nodes (nodes without children), most store values also in internal nodes (nodes with children).
But that will of course get us nowhere, since we only add one item, and we don't even know where in all the values this specific value is, so it could be the first, or the last, or any in between.
But, we know that if the root node has children in the left "direction", then any values we might find in all those nodes will come before the node in the root node.
And we also know that if the root node has children in the right "direction", those values will come after it.
So what we can do is this:
- Process all nodes in the left sub-tree
- Append the value in the node
- Process all nodes in the right sub-tree
This approach assumes that:
- Node values are ordered (ie. left sub-tree comes before the value of the node itself, etc.)
- You want the values in their ordered sequence
If you define the above approach as a method, you'll have something like this:
to process a node, do this:
first process the left-child sub-node, if present
then append the value of the node, if any
then process the right-child sub-node, if present
In the above pseudo-code, where you see the word "process", you apply the same process to those nodes as described above.
Here's the C# code to process a simple binary tree and append the result to a given linked list:
public void AppendTreeToLinkedList<T>(Node<T> node, LinkedList<T> list)
{
if (node.LeftChild != null)
AppendTreeToLinkedList(node.LeftChild, list);
list.Append(node.Value);
if (node.RightChild != null)
AppendTreeToLinkedList(node.RightChild, list);
}