看了网上很多代码,又各种各样的实现方式,有一些不是很容易理解,自己写了一个,贴出来:
Code:
struct BSTreeNode
{
int m_nValue; // value of node
BSTreeNode *m_pLeft; // left child of node
BSTreeNode *m_pRight; // right child of node
};
//Create the tree
void insertChild(BSTreeNode*& pNode,int value) {
if( pNode == NULL ) {
pNode = new BSTreeNode();
pNode->m_nValue = value;
pNode->m_pLeft = NULL;
pNode->m_pRight = NULL;
}
if( pNode->m_nValue > value ) insertChild( pNode->m_pLeft, value );
else if( pNode->m_nValue < value ) insertChild( pNode->m_pRight, value );
}
void BinaryTreePrint(BSTreeNode* node)
{
BSTreeNode *temp = node;
if(temp == NULL)
return;
BinaryTreePrint( node->m_pLeft );
cout<<temp->m_nValue<<“->”;
BinaryTreePrint( node->m_pRight );
}
//Convert Binary search tree to double list
BSTreeNode* header = NULL;
BSTreeNode* current = NULL;
void ConvertToDList(BSTreeNode* root) {
BSTreeNode* temp = root;
if( temp == NULL )
return;
ConvertToDList( temp->m_pLeft );
if( header == NULL ) {
header = temp;
current = temp;
}
else {
current->m_pRight = temp;
temp->m_pLeft = current;
current = temp;
cout<<current->m_nValue<<” “;
}
ConvertToDList( temp->m_pRight );
}
int main(int argc, char* argv[])
{
BSTreeNode* root;
insertChild( root, 15 );
insertChild( root, 17 );
insertChild( root, 12 );
insertChild( root, 10 );
insertChild( root, 7 );
insertChild( root, 19 );
insertChild( root, 21 );
insertChild( root, 24 );
insertChild( root, 35 );
BinaryTreePrint( root );
ConvertToDList( root );
NodeListPrint( header );
return 0;
}