微软笔试题:
输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。
要求不能创建任何新的结点,只调整指针的指向。
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
void addBSTreeNode(BSTreeNode* pCurrent, int value)
{
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)
{
addBSTreeNode(pCurrent->lchild, value);
}
else if((pCurrent->value) < value)
{
addBSTreeNode(pCurrent->rchild, 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
{
Head = pCurrent;
}
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;
Head = NULL;
addBSTreeNode(pRoot, 10);
addBSTreeNode(pRoot, 4);
addBSTreeNode(pRoot, 6);
addBSTreeNode(pRoot, 8);
addBSTreeNode(pRoot, 12);
addBSTreeNode(pRoot, 14);
addBSTreeNode(pRoot, 15);
addBSTreeNode(pRoot, 16);
ergodicBSTree(pRoot);
system("pause");
return 0;
}