您的位置:首页 > Web前端

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

2016-06-09 21:36 453 查看
题目:输入一课二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
因为树的结构和循环链表的结构十分类似,所以使它们之间的转换成为了可能。

具体方法:
原先指向左子结点的指针调整为链表中指向前一节点的指针;原先指向右子结点的指针调整为链表中指向后一个结点的指针。

因为要求转换之后的链表时排好序的,所以我们可以借助中序遍历。当遍历的时候我们将树看成三部分:根节点,左子树,右子树。

如下图:





具体实现代码如下;
#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;
}

运行结果如下:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: