将二叉搜索树转换成双向链表

#include <iostream>
#include <vector>  
using namespace std;  
  
struct node{
    int data;
    node* lchild;
    node* rchild;
};
                    
node* buildBTree(int* a, int &i)
{
    if(a==NULL || a[i]==-1)
        return NULL;
    node* p = new node;
    p->data = a[i];
    p->lchild = buildBTree(a, ++i);
    p->rchild = buildBTree(a, ++i);
    return p;
}

void preOrder(node* r)
{
    if(r!=NULL)
    {
        cout<<r->data<<" ";
        preOrder(r->lchild);
        preOrder(r->rchild);
    }else{
        cout<<-1<<" ";
    }
}

node* buildBTree()
{
    int a[] = {8, 6, -1, 7, -1, -1, 10, 9, -1, -1, 11, -1, -1};
    int i=0;
    return buildBTree(a, i);
}

node* double_link(node* r, node*& left, node*& right)
{
    if(r == NULL)
        return r;
    node *ll, *lr, *rl, *rr, *lp, *rp;
    if(r->lchild==NULL)
    {
        left = r;
    }
    else
    {
        lp = double_link(r->lchild, ll, lr);
        left = ll;
        r->lchild = lr;
        lr->rchild = r;
    }

    if(r->rchild==NULL)
    {
        right = r;
    }
    else
    {
        rp = double_link(r->rchild, rl, rr);
        right = rr;
        r->rchild = rl;
        rl->lchild = r;
    }
    return r;
}

int main()  
{  
    node* r = buildBTree(); 
    node *left, *right;
    node *h;
    double_link(r, left, right);
    h = left;
    while(h->rchild)
    {
        cout<<h->data<<" ";
        h = h->rchild;
    }
    cout<<h->data<<endl;
    while(h->lchild)
    {
        cout<<h->data<<" ";
        h = h->lchild;
    }
    cout<<h->data<<endl;
    return 0;  
}  

点赞