When I see this question, I think the first thing I think is to traverse the binary tree in the middle order.
However, it is difficult to create a linked list. If you don't read a book, you can't do it.
The method used is to traverse in the middle order, right after recursion, 8 at the last node of the Left subtree at this time, the root node is 10, and has not yet entered the right subtree recursion.
Then, you only need to create a linked list of 8 and 10. Then, how can we deal with the right subtree? You must have the first node 10 before it can be entered, because it is in the middle order, when traversing to the last node is 12, if the last node is 10, it can be connected. Think about it. Isn't the middle-order traversal the 12 output after 10, so here is the expected result.
As for what the material is, of course, the recursive traversal of each central order is saved to the previous node. The last node of the Left subtree needs to establish a relationship with the root node.
Soga, coding
#include "stdio.h"typedef struct Node{ int key; struct Node *left; struct Node *right;}Lnode;void buildTree(Lnode **head){Lnode *p=NULL;int value;scanf("%d",&value);if(value ==-1){*head=NULL;}else{p = (Lnode *)malloc(sizeof(Lnode));p->key = value;*head=p;buildTree(&((*head)->left));buildTree(&((*head)->right));}return;}void traverse(Lnode *p){if(p==NULL)return;printf("%d ",p->key);traverse(p->left);traverse(p->right);}void traverseList(Lnode *p){while(p!=NULL){printf("%d ",p->key);p=p->right;}}void convertList(Lnode *head,Lnode **lastNode){Lnode *current = head;if(head == NULL)return;if(head->left)convertList(head->left,lastNode);head->left = *lastNode;if(*lastNode != NULL)(*lastNode)->right=head;*lastNode=current;if(head->right)convertList(head->right,lastNode);}Lnode *buildDouble(Lnode *head){Lnode *lastNode = NULL;Lnode *p=NULL;convertList(head,&lastNode);p=lastNode;while(p->left != NULL){p=p->left;}return p; }int main(){Lnode *head=NULL;Lnode *listHead=NULL;int totalNum= 10;int index =0;int value=0;buildTree(&head);traverse(head);printf("\n");listHead = buildDouble(head);traverseList(listHead);printf("\n");return 0;}
This question is very good.
1 Recursion
2 trees
3 Traversal
These three properties are combined to test, truly awesome