0

I am currently working on an assignment for a comp sci class that requires me to implement a bunch of different functions with binary search trees. The current function that I am having trouble wrapping my head around goes through the tree and recursively splits it into a pointer to two separate trees. I am generally just confused on how to do this with pointers to pointers to Node objects (which is how he set up the function when he gave us the assignment)

void split(Node *T, int k, Node **L, Node **R)
{
    if(T == nullptr){

    }
    else{
        if(T->key <= k){
            Node *RightL;
            Node *RightR;
            Node *temp = T;
            split(T->right,k,&RightL,&RightR);
            temp->right = nullptr;
            temp->right = RightL;
            R = &RightR;
            L = &temp;
        }
        else{
            Node *LeftL;
            Node *LeftR;
            Node *temp = T;
            split(T->left,k,&LeftL,&LeftR);
            temp->left = nullptr;
            temp->left = LeftR;
            R = &temp;
            L = &LeftL;
        }
    }
}

As far as the logic of this, he described that if the key/value of the current tree node is less than the value given when the function is called it should take the current node along with all its left tree contents and put it into the left tree and then take the resulting left side after splitting the right branch and set it to the missing right branch of the left tree. The right branch of the split right branch is then assigned to the right tree.

How can I rewrite what I currently have to make it work?

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
  • You are passing uninitialized pointers. You need left and right to be nullptr until they actually have a node to serve as the tree root. Think of it as removing all the nodes from the original tree, and building two new trees from scratch. You can use your "add" function to build those two new trees. – Kenny Ostrom Mar 13 '20 at 17:38
  • Try making the `Node` type super-safe on its own. Just make sure that passing it around will not make the program have undefined behavior. When you have that `Node`, adding content to it is sort of done. You have the [rule of five](https://en.cppreference.com/w/cpp/language/rule_of_three) to adhere to in this case. – Ted Lyngmo Mar 13 '20 at 18:16

0 Answers0