算法-平衡查找树变换为双向链表

看了网上很多代码,又各种各样的实现方式,有一些不是很容易理解,自己写了一个,贴出来:

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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值