方法很简单,就是建树,然后因为是二叉搜索树,所以中序遍历就是排序好的了
开始天真,想错了
也是中序的思想,然后创建链表指针
#include<cstdio>
#include<cstring>
#include<cstdlib>
typedef struct node
{
int val;
struct node *left;
struct node *right;
struct node *pre,*next;
}Tree;
void createTree(Tree *(*b))
{
int val;
scanf("%d",&val);
if(val != 0)
{
Tree *s = (Tree *)malloc(sizeof(Tree));
s->val = val;
s->right = NULL;
s->left = NULL;
s->pre = NULL;
s->next = NULL;
*b = s;
createTree(&((*b)->left));
createTree(&((*b)->right));
}
else
{
*b = NULL;
}
}
void createList(Tree *tree,Tree **list)
{
if(list == NULL)
return ;
Tree *current = tree;
if(tree->left != NULL)
createList(tree->left,list);
current->pre = *list; //中序遍历
if(*list != NULL)
(*list)->next = current;
*list = current;
if(tree->right != NULL)
createList(tree->right,list);
}
void printList(Tree *list)
{
if(list == NULL)
return;
while(list->pre != NULL)
{
list = list->pre;
}
while(list != NULL)
{
printf("%d ",list->val);
list = list->next;
}
printf("\n");
}
int main()
{
int T;
while(scanf("%d",&T) != EOF)
{
while(T--)
{
Tree *tree = (Tree *)malloc(sizeof(Tree));
createTree(&tree);
Tree *list = NULL;
createList(tree,&list);
// if(list == NULL)
// printf("--");
printList(list);
}
}
return 0;
}