二元查找树转换成双向链表

输入一颗二元查找树,将该二元查找树转换成一个排序的双向链表,要求不能创建任何新的结点,只调整指针的指向。

 比如将二元查找树

转换成双向链表4=6=8=10=12=14=16。

#include<iostream>
using namespace std;
struct BSTreeNode
{
	int m_nValue;
	BSTreeNode *m_pleft;
	BSTreeNode *m_pright;
};


void addBSTreeNode(BSTreeNode *&pCurrent,int value);
void inOrderBSTree(BSTreeNode* pBSTree);
void convertToDoubleList(BSTreeNode* pCurrent);
 
BSTreeNode *pHead=NULL;//指向循环队列头结点
BSTreeNode *pIndex=NULL;//指向前一个结点

int main()
{
    BSTreeNode *pRoot=NULL;
    addBSTreeNode(pRoot,10);
    addBSTreeNode(pRoot,6);
    addBSTreeNode(pRoot,14);
    addBSTreeNode(pRoot,4);
    addBSTreeNode(pRoot,8);
    addBSTreeNode(pRoot,12);
    addBSTreeNode(pRoot,16);
    inOrderBSTree(pRoot);
	system("pause");
    return 0;
}

//函数参数一定要用引用,这是因为要改变指针的值,否则只改变指针所指向地址的内容 void addBSTreeNode(BSTreeNode *&pCurrent,int value) { if(pCurrent==NULL) { BSTreeNode *pBSTree = new BSTreeNode(); pBSTree->m_nValue = value; pBSTree->m_pleft = NULL; pBSTree->m_pright = NULL; pCurrent = pBSTree; } else if(pCurrent->m_nValue < value) addBSTreeNode(pCurrent->m_pright,value); else if(pCurrent->m_nValue > value) addBSTreeNode(pCurrent->m_pleft,value); else cout<<"node repeated"<<endl; } void inOrderBSTree(BSTreeNode *pBSTree) { if(NULL==pBSTree) return; if(NULL != pBSTree->m_pleft) inOrderBSTree(pBSTree->m_pleft); convertToDoubleList(pBSTree); if(NULL != pBSTree->m_pright) inOrderBSTree(pBSTree->m_pright); } void convertToDoubleList(BSTreeNode *pCurrent) { pCurrent->m_pleft = pIndex; if(NULL == pIndex) pHead = pCurrent; else pIndex->m_pright = pCurrent; pIndex = pCurrent; cout<<pCurrent->m_nValue<<" "; }

  

 

posted @ 2013-10-24 16:32  我爱写程序  阅读(285)  评论(0编辑  收藏  举报