《剑指offer》:[27]二叉搜索树与双向链表的转化过程

题目:输入一课二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。

因为树的结构和循环链表的结构十分类似,所以使它们之间的转换成为了可能。

具体方法:
原先指向左子结点的指针调整为链表中指向前一节点的指针;原先指向右子结点的指针调整为链表中指向后一个结点的指针。
因为要求转换之后的链表时排好序的,所以我们可以借助中序遍历。当遍历的时候我们将树看成三部分:根节点,左子树,右子树。

如下图:


具体实现代码如下;
#include <iostream>
using namespace std;
struct BinaryTree
{
	int data;
	BinaryTree *pLeft;
	BinaryTree *pRight;
};
int arr[7]={4,2,6,1,3,5,7};
BinaryTree *pRoot=NULL;


void InsertTree(BinaryTree *root,int data)
{
	BinaryTree *node=root;
	if(node->data > data)
	{
		if(NULL==node->pLeft)
		{
			BinaryTree *pNode=new BinaryTree;
			pNode->data=data;
			pNode->pLeft=pNode->pRight=NULL;
			node->pLeft=pNode;
		}	
		else
			InsertTree(node->pLeft,data);
	}
	else
	{
		if(NULL==node->pRight)
		{
			BinaryTree *pNode=new BinaryTree;
			pNode->data=data;
			pNode->pLeft=pNode->pRight=NULL;
			node->pRight=pNode;
		}
		else
			InsertTree(node->pRight,data);
	}
}
void CreateTree(BinaryTree **root,int *array,int length)
{
	for(int i=0;i<7;i++)
	{
		if(NULL==*root)
		{
			BinaryTree *pNode=new BinaryTree;
			pNode->data=array[0];
			pNode->pLeft=pNode->pRight=NULL;
			*root=pNode;
		}
		else
		{
			InsertTree(*root,array[i]);
		}
	}
}
void PreOrder(BinaryTree *root)
{
	BinaryTree *temp=root;
	if(temp)
	{
		cout<<temp->data<<" ";
		PreOrder(temp->pLeft);
		PreOrder(temp->pRight);
	}
}
void ConvertHelp(BinaryTree *pNode,BinaryTree **pLastnode)
{
	if(pNode==NULL)
		return ;
	BinaryTree *current=pNode;
	if(current->pLeft!=NULL)
		ConvertHelp(current->pLeft,pLastnode);
	current->pLeft=*pLastnode;
	if(*pLastnode!=NULL)
		(*pLastnode)->pRight=current;
	*pLastnode=current;
	if(current->pRight!=NULL)
		ConvertHelp(current->pRight,pLastnode);
}
BinaryTree *Convert(BinaryTree *root)
{
	BinaryTree *pLastNode=NULL;//指向双向链表的尾结点;
	ConvertHelp(root,&pLastNode);
	//返回头结点
	BinaryTree *pHeadList=pLastNode;
	while(pHeadList!=NULL && pHeadList->pLeft!=NULL)
		pHeadList=pHeadList->pLeft;
	return pHeadList;
}
void showList(BinaryTree *list)
{
	BinaryTree *head=list;
	while(head)
	{
		cout<<head->data<<" ";
		head=head->pRight;
	}
}
int main()
{
	CreateTree(&pRoot,arr,7);
	cout<<"树的前序遍历:";
	PreOrder(pRoot);
	cout<<endl<<"循环链表的遍历:";
	showList(Convert(pRoot));
	cout<<endl;
	system("pause");
	return 0;
}

运行结果如下:






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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值