3

I am building a binary search tree and the following is the add function:

void BinaryTree::add(int value, Node*& node, Node*& parent) {
    if(!node) {
        node = new Node(value);
        node->parent = parent;
    }
    else if(node->key < value)
        this->add(value, node->rightNode, node);
    else if(node->key > value)
        this->add(value, node->leftNode, node);
}

I want to set default parameters for the last two (node, parent) parameters:

void add(int value, Node*& node = root , Node*& parent = nullptr);

where root is a field of the class.

This does not seem to work for either case. How shall I implement it and what is wrong here? Thanks!

roalz
  • 2,699
  • 3
  • 25
  • 42
Ra1nWarden
  • 1,170
  • 4
  • 21
  • 37

1 Answers1

5

You can't initialize references to nullptr. They has to be valid objects. To make root defualt object you may add new function with same name

void BinaryTree::add(int value) {
    Node* emptyParent = nullptr;
    add(value, root, emptyParent); 
}
RiaD
  • 46,822
  • 11
  • 79
  • 123