聲明:取自 」july「的「微軟100題「,加上一些我的理解,歡迎拍磚。
ios
原文地址:http://blog.csdn.net/v_july_v/article/details/6126406學習
學習微軟100題筆記:spa
1.二元查找樹變雙向鏈表:.net
#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 );
blog
if( NULL != pCurrent->m_pRight )遞歸
{
ergodicBSTree( pCurrent->m_pRight );
}it
}io
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大神。