把二叉树转换成双向链表

// 把二叉树转换成双向链表.

struct BinaryTreeNode
{
    int m_nValue;
    BinaryTreeNode *m_pLeft;
    BinaryTreeNode *m_pRight;
public:
    BinaryTreeNode(int v):m_nValue(v),m_pLeft(NULL),m_pRight(NULL){}
};
void Convert(BinaryTreeNode *t,BinaryTreeNode **head,BinaryTreeNode **last)
{
    BinaryTreeNode *lh,*ll,*rh,*rl;
    if(t!=NULL)
    {
        Convert(t->m_pLeft,&lh,&ll);
        if(ll==NULL)
        {
            *head=t;
        }
        else
        {
            *head=lh;
            ll->m_pRight=t;
            t->m_pLeft=ll;
        }
        Convert(t->m_pRight,&rh,&rl);
        if(rh==NULL)
        {
            t->m_pRight=NULL;
            *last=t;
        }
        else
        {
            t->m_pRight=rh;
            rh->m_pLeft=t;
            *last=rl;
        }
    }
    else
    {
        *head=NULL;
        *last=NULL;
    }
}
    BinaryTreeNode b1(10),b21(6),b22(14),b31(4),b32(8),b33(12),b34(16);

    void printMidOrder(BinaryTreeNode *t)
    {
        if(t)
        {
            printMidOrder(t->m_pLeft);
            cout<<setw(5)<<t->m_nValue;
            printMidOrder(t->m_pRight);
        }
    }
void main()
{ 


    b1.m_pLeft=&b21;
    b1.m_pRight=&b22;
    b21.m_pLeft=&b31;
    b21.m_pRight=&b32;
    b22.m_pLeft=&b33;
    b22.m_pRight=&b34;
    BinaryTreeNode *head,*last;
    printMidOrder(&b1);
    Convert(&b1,&head,&last);
    // 输出转换结果
    BinaryTreeNode *p=head;
    while(p!=NULL)
    {
        cout<<setw(5)<<p->m_nValue;
        p=p->m_pRight;
    }
    system("pause");
}
原文地址:https://www.cnblogs.com/dyc0113/p/3211957.html