I am trying to convert a binary search tree to a linked list. The linked list should have the smaller numbers in the front and the larger numbers in the back (smallest to largest). I need to create a function that takes in a binary search tree tree and outputs a linked list.
4
/ \
2 6
/ \ / \
1 3 5 7
Here's my binary search tree. I need to make the linked list this way: 1, 2, 3, 4, 5, 6, 7. Here's my current code:
node<int>* makeLinkedList(binary_tree_node<int>* root_ptr);
int main()
{
binary_tree_node<int> *s1 = sample1(); //Creates the tree
node<int>* node1 = makeLinkedList(s1); //invokes function to make a linked list
//Loop to print out the values of the linked list
for (node1; node1 != NULL; node1 = node1->link()){
cout<<node1->data()<<endl;
}
}
node<int>* makeLinkedList(binary_tree_node<int>* root_ptr){
node<int>* left;
if (root_ptr == NULL) {
return NULL;
}
else{
left = makeLinkedList(root_ptr->left());
list_head_insert(left, root_ptr->data()); //list_head_insert inserts a new entry at the head of the linked list
return left;
}
}
When I run my code, the output is 4, 2, 1. I just don't understand how I can convert this binary search tree into a linked list from smallest to largest. I've tried putting list_head_insert function on top of the recursive call, but the output is nothing and the list is empty.