题目1503:二叉搜索树与双向链表

方法很简单,就是建树,然后因为是二叉搜索树,所以中序遍历就是排序好的了

开始天真,想错了

也是中序的思想,然后创建链表指针

#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;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值