Konwertowanie DLL do zbalansowanego drzewa BST

0

Witam, mam problem z napisaniem funkcji, które będzie zamieniała listę dwukierunkową w drzewo BST. Kompilator jednak wyrzuca mi cały czas błędy i funkcja rekurencyjna się nie kończy.

struct node{
    int value;
    node *left,*right,*parent;
};

node *getMid(node *head)
{
    node *result=head;
    while(head){
        head=head->right;
        if(head){
            head=head->right;
            result=result->right;
        }
    }
    return result;
}

void PrintBST(node *root)
{
    if(root){
        PrintBST(root->left);
        cout<<root->value<<" ";
        PrintBST(root->right);
    }
}

node *BuildTree(node *root)
{
   if(!root) return root;
   node *Mid=getMid(root);
   cout<<Mid->value<<endl;
   if(!Mid->left) cout<<"X"<<endl;
   node *l=Mid->left;
   //cutting DLL
   if(l) l->right=nullptr;
   if(Mid->right) Mid->right->left=nullptr;

   Mid->left=BuildTree(root);
   if(Mid->left) Mid->left->parent=Mid;

   Mid->right=BuildTree(Mid->right);
   if(Mid->right) Mid->right->parent=Mid;

   return Mid;
}

Bardzo proszę o pomoc w znalezieniu błędu ;)

0

Problem rozwiązany.

1

Jeśli ktoś kiedyś będzie tego szukał to tu jest rozwiązanie:

node *BuildTree(node *root)
{
    if(!root) return nullptr;
   if(!root->left and !root->right) {
        return root;
   }
   node *Mid=getMid(root);
   if(!Mid->left and !Mid->right) return Mid;
   node *l=Mid->left;
   //cutting DLL
   if(l) l->right=nullptr;
   if(Mid->right) Mid->right->left=nullptr;

   Mid->left=BuildTree(root);
   if(Mid->left) Mid->left->parent=Mid;

   Mid->right=BuildTree(Mid->right);
   //if(Mid->right) Mid->right->parent=Mid;

   return Mid;
}

1 użytkowników online, w tym zalogowanych: 0, gości: 1