参考了July的博客,然后自己动手实现了一线,留着备忘吧!
题目:
输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。
要求不能创建任何新的结点,只调整指针的指向。
10
/ \
6 14
/ \ / \
4 8 12 16
转换成双向链表
4=6=8=10=12=14=16。
#include <iostream>
#include <cstdio>
using namespace std;
struct BSTreeNode //存储二叉查找树节点信息
{
int val;
BSTreeNode *lchild,*rchild;
};
typedef BSTreeNode DoubleList;
DoubleList *pHead,*pLastIndex; //pHead存储头节点,pLaseIndex存储上一个插入的节点
//中序序列创建二叉查找树
void CreateBSTree(BSTreeNode * & pCurrent,int val) //pCurrent是一个BSTreeNode*类型的引用
{
if(NULL == pCurrent)
{
BSTreeNode *temp=new BSTreeNode() ;
temp->val = val ;
temp->lchild = NULL , temp->rchild = NULL ;
pCurrent = temp ;
}
else
{
if(pCurrent->val > val)
CreateBSTree(pCurrent->lchild,val);
else if(pCurrent->val < val)
CreateBSTree(pCurrent->rchild,val);
else cout<<"输入数据重复"<<endl;
}
}
void ConvertToDoubleList(BSTreeNode *node); //将二叉树转换为双向链表
//中序遍历二叉查找树
void InorderBSTree(BSTreeNode *pCurrent)
{
if(pCurrent == NULL) return;
if(pCurrent->lchild != NULL)
InorderBSTree(pCurrent->lchild);
ConvertToDoubleList(pCurrent);
if(pCurrent->rchild != NULL)
InorderBSTree(pCurrent->rchild);
}
void ConvertToDoubleList(BSTreeNode *node)
{
node->lchild = pLastIndex ;
if(pLastIndex == NULL)
pHead = node ;
else
pLastIndex->rchild = node ;
pLastIndex = node ;
cout<<" "<<node->val<<endl;
}
int main()
{
BSTreeNode *pRoot ;
pRoot = pHead = pLastIndex = NULL ;
CreateBSTree(pRoot,4);
CreateBSTree(pRoot,10);
CreateBSTree(pRoot,6);
CreateBSTree(pRoot,16);
CreateBSTree(pRoot,14);
CreateBSTree(pRoot,12);
CreateBSTree(pRoot,8);
InorderBSTree(pRoot);
return 0;
}