二元查找树变双向链表

声明:取自 ”july“的“微软100题“,加上一些个人理解,欢迎拍砖。

原文地址:http://blog.csdn.net/v_july_v/article/details/6126406


学习微软100题笔记:

1.二元查找树变双向链表:

#include <stdio.h>
#include <iostream>


struct BSTreeNode
{
    int m_nValue; 
    BSTreeNode *m_pLeft; 
    BSTreeNode *m_pRight; 
};


typedef BSTreeNode DoubleList;
DoubleList * pHead;
DoubleList * pListIndex;


void convertToDoubleList(BSTreeNode * pCurrent);


BSTreeNode* addBSTreeNode(BSTreeNode * & pCurrent, int value)
{
    if (NULL == pCurrent)
    {
        pCurrent = new BSTreeNode();
        pCurrent->m_pLeft = NULL;
        pCurrent->m_pRight = NULL;
        pCurrent->m_nValue = value;
    }
    else if( pCurrent->m_nValue > value )
    {
        pCurrent->m_pLeft = addBSTreeNode( pCurrent->m_pLeft, value );
}
else if ( pCurrent->m_nValue< value )
{
        pCurrent->m_pRight = addBSTreeNode(pCurrent->m_pRight, value);
}   
else
    {
std::cout<<"重复加入节点"<< std::endl;
    }


return pCurrent;
}

void ergodicBSTree( BSTreeNode *pCurrent )
{
if( NULL == pCurrent )
{
return;
}
if( NULL != pCurrent->m_pLeft )
{
ergodicBSTree( pCurrent->m_pLeft );

}


convertToDoubleList( pCurrent );


if( NULL != pCurrent->m_pRight )

{
ergodicBSTree( pCurrent->m_pRight );
}

}



void convertToDoubleList( BSTreeNode *pCurrent )
{
pCurrent->m_pLeft = pListIndex;
if( NULL != pListIndex )
{
pListIndex->m_pRight = pCurrent;
}
else
{
pHead = pCurrent;
}


pListIndex = pCurrent;


std::cout << pCurrent->m_nValue << std::endl;
}


int
main( void )
{
BSTreeNode *pRoot = NULL;
pListIndex = NULL;
pHead = 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);
    return 0;
}


其中建立二叉树时是按照 c语言程序设计中(K&R)方法建立的,大同小异。

重点是利用递归转换为链表的过程。

一个全局指针pListIndex指向pCurrent的前一个节点,每次调用convertToDoubleList完成

pCurrent->m_pRight -> pListIndex;因为这里pCurrent不为NULL,然后再pListIndex->m_pLift 指向当前pCurrent

要先判断pListIndex是否为NULL,因为pListIndex开始时是赋值为NULL的,不能进行解引用操作。




新手没经验,欢迎指正错误,待更新。详细请见开头原博文 ,july大神。

posted @ 2016-03-18 08:56  mr_yu  阅读(302)  评论(0编辑  收藏  举报