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

来源:互联网 发布:淘宝靠谱的单反店铺 编辑:程序博客网 时间:2024/06/06 09:46

微软笔试题:

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

要求不能创建任何新的结点,只调整指针的指向。
  
   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 treevoid 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;}


注:程序有点问题,需要修改

原创粉丝点击