# 输入一棵二元查找树，将该二元查找树转换成一个排序的双向链表

10
/ \
6  14
/ \ / \
4  8 12 16

4=6=8=10=12=14=16。

1）定义二叉树节点

typedef struct BSTreeNode
{
int value;
struct BSTreeNode *lchild;
struct BSTreeNode *rchild;
}BSTreeNode;


2）建立二分查找树，二分查找树的建立流程图如下：

//Create the binary tree
{
if(NULL == pCurrent)
{
BSTreeNode *pBSTree = (BSTreeNode*)malloc(sizeof(BSTreeNode));
pBSTree->lchild = NULL;
pBSTree->rchild = NULL;
pBSTree->value = value;
pCurrent = pBSTree;
}
else
{
if((pCurrent->value) > value)
{
}
else if((pCurrent->value) < value)
{
}
else
{
printf("Wrong, Repeated insert the node");
}
}
}

3）对建立的二叉查找树进行到双向链表的转换

// convert binary tree to list.
void convertToDoubleList(BSTreeNode *pCurrent)
{
pCurrent->lchild = ListIndex;
if(NULL != ListIndex)
{
ListIndex->rchild = pCurrent;
}
else
{
}
ListIndex = pCurrent;
printf("%d\n",pCurrent->value);
}

// ergodic the binary tree using inorder.
void ergodicBSTree(BSTreeNode *pCurrent)
{
if(NULL == pCurrent)
{
return;
}
if(NULL != pCurrent->lchild)
{
ergodicBSTree(pCurrent->lchild);
}

convertToDoubleList(pCurrent);

if(NULL != pCurrent->rchild)
{
ergodicBSTree(pCurrent->rchild);
}
}

4）主函数如下：

int main()
{
BSTreeNode *pRoot = NULL;
ListIndex = NULL;

ergodicBSTree(pRoot);

system("pause");
return 0;
}

• 评论

• 下一篇
• 上一篇