Set default parameter to nullptr and non-static class fields in C++ - c++

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!

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);
}

Related

How to create insert function in BST without specifying root as parameter

I've been given a task to create a method of Binary Search Tree class to insert elements in the correct place in the tree. The declaration of this function is:
void BST::insert(int k)
{
}
Can someone explain why isn't a root node given as parameter ? How am i able to traverse the tree, when I do not have its root node ? Having a return type of void hints me to use the 'this' keyword
I've tried implementing the following:
void BST::insert(int k) {
while(this->root != NULL) {
if(k < this->root->value) {
this->root = this->root->leftChild;
} else {
this->root = this->root->rightChild;
}
}
this->root = new node(k);
}
This is additionnal OOP code:
struct node {
int value;
node* parent;
node* leftChild;
node* rightChild;
node (int);
int dessiner(ofstream&, int);
};
class BST {
public:
node* root;
BST();
void dessiner(string);
void swap(node*, node*);
void inserer(int);
};
EDIT: I added 2 pointers. tmp to traverse tree and P to keep track of tmp's parent node
node* tmp = this->root;
node* p = NULL;
while(tmp!=NULL) {
p = tmp;
if(k < tmp->value) {
tmp = tmp->leftChild;
} else {
tmp = tmp->rightChild;
}
}
tmp = new node(k);
tmp->parent = p;
Can someone explain why isn't a root node given as parameter ?
It is. BST::insert implicitly has a BST * parameter, named this. From there you can get at root. Note that you don't need this-> to refer to root, it is implicit in body of the member function.
Having a return type of void hints me to use the 'this' keyword
The return type has nothing to do with it.
Note that you will need to assign the new node to p's leftChild or rightChild, after insert finishes, nothing points to it.
When dealing with BSTs I usually write a public function like the one you have which calls a the private, recursive function with the root of the tree. You don't have access to the root of the tree from outside the class so it doesn't make sense for the public function to accept anything more than the element to insert.
void BST::insert(int k)
{
insert(k, root);
}
void BST::insert(int k, node* curr)
{
// logic to insert the new element
...
}
You can combine these functions with a default parameter so from outside the class you can call bst.insert(5) and curr will start out as the root of the tree.
void BST::insert(int k, node* curr = root)
{
// logic to insert the new element
...
}

C++ Binary Search Tree Insert Implementation

I'm trying to build a function to insert into a binary search tree, but I'm having a hard time figuring out why it won't work. I understand fundamentally how the function is supposed to work, but based on the template I was given it seems as though I am to avoid creating a BST class but instead rely on the Node class and build the desired functions to work on that. Here's the given template:
#include <iostream>
#include <cstddef>
using std::cout;
using std::endl;
class Node {
int value;
public:
Node* left; // left child
Node* right; // right child
Node* p; // parent
Node(int data) {
value = data;
left = NULL;
right = NULL;
p = NULL;
}
~Node() {
}
int d() {
return value;
}
void print() {
std::cout << value << std::endl;
}
};
function insert(Node *insert_node, Node *tree_root){
//Your code here
}
The issue I'm having is when I implement the following code, where getValue is a simple getter method for Node:
int main(int argc, const char * argv[]) {
Node* root = NULL;
Node* a = new Node(2);
insert(a, root);
}
void insert(Node *insert_node, Node *tree_root){
if (tree_root == NULL)
tree_root = new Node(insert_node->getValue());
The code appears to compile and run without error, but if I run another check on root after this, it returns NULL. Any idea what I'm missing here? Why is it not replacing root with a new node equal to that of insert_node?
I also realize this doesn't appear to be the optimal way to implement a BST, but I am trying to work with the template given to me. Any advice would be appreciated.
As Joachim said your issue relates to difference between passing parameter by reference and by value.
In your code void insert(Node *insert_node, Node *tree_root) you pass Node* tree_root by value. Inside the function you change local copy of this pointer, so outer value is not changed.
To fix it you should pass Node* tree_root by reference. Parameter declaration can be Node*& tree_root (or Node** tree_root). E.g:
void insert(Node* insert_node, Node*& tree_root){
if (tree_root == NULL)
tree_root = new Node(insert_node->getValue());

Linked list,Confused about Function that adds node to head of the list

I have a question about a function that adds a creates/adds a new node to the top of the list. Here is the set up.
A head is created in the main program. We set the list to Null
IntNode* head = new IntNode(3,NULL);
My question is about the function that adds a node to the top of the list. Assumes that there is at least one node in the list.(the one we just created)
void headInsert(IntNodePtr& head, int theData)
{
head = new IntNode(theData, head);
}
I know it creates a new node and makes the pointer already declared in the main program, which is passed, point to the new node. However I am confused about he "head" part on the parameter in the constructor(not the headInsert function). I am confused about what exactly is being passed when we pass head in the IntNode constructor above. That head sets the variable link, to point to what head is pointing to correct? ******My question is, Does it first set *link(the class variable) to point to what head is pointing to, in this case the node with the number 3 whose list points to NULL, AND THEN makes head point to the new NODE? So in other words the right part of the assignment is done first? I'm just very confused as to what is being passed in when we create the new node.
class IntNode
{
public:
IntNode( ) {}
IntNode( int theData, IntNode* theLink)
: data(theData), link(theLink) {}
IntNode* getLink( ) const { return link; }
int getData( ) const { return data; }
void setData( int theData) { data = theData; }
void setLink(IntNode* pointer) { link = pointer; }
private:
int data;
IntNode *link;
};
void headInsert(IntNodePtr& head, int theData)
{
head = new IntNode(theData, head);
}
The evaluation of the sides of the assignment -
head
and
new IntNode(theData, head)
is not ordered at all, but prior to performing the assignment, both sides have been evaluated completely.
Since neither side modifies the value of head, the results are the same regardless of the order of evaluation.

Appending node to LinkedList

I am trying to create a function that adds a node to the end of a LinkedList. I know how to do it using loops, but my professor wants it done a certain way and I don't understand why it's not working. He practically gave us all the code for it..
This is the pseudo-code he gave us:
process append(data)
if (not the end)
next->append(data);
else
next=new Node();
next->data=data;
next->data = nullptr;
And this is what I came up with:
struct Node {
int data;
Node* next;
};
struct LinkedList {
Node* head;
LinkedList() {head = nullptr;}
void prepend(int data) {
if (head == nullptr) {
Node* tmp = new Node();
tmp->data=data;
tmp->next=nullptr;
}
else {
Node* tmp = new Node();
tmp->data=data;
tmp->next=head;
head=tmp;
}
}
void append(int data) {
Node* tmp = head;
if (tmp->next != nullptr) {
tmp=tmp->next->append(data);
}
else {
tmp->next = new Node();
tmp->next->data = data;
tmp->next->next = nullptr;
}
}
};
int main()
{
LinkedList LL = LinkedList();
LL.prepend(7);
LL.append(6);
std::cout << LL.head->data << std::endl;
}
My prepend (to add to the beginning of the LinkedList) works fine, but when I try this code, I get
main.cpp:48:20: error: 'struct Node' has no member named 'append'
tmp->next->append(data);
So I'm pretty sure that there's something wrong with saying next->append(data), which from what I understood, is supposed to be recursively calling back the append function until it reaches a nullpointer. I'm thinking maybe there's some sort of way to write it, but people in my class are telling me that the next->append(data) thing SHOULD work, so I guess I'm not exactly sure why this isn't doing anything. I tried instead writing the append function in the Node struct, but then it says that head wasn't declared in the scope and I really just don't know how to work with this. I'm also sort of new to classes/structs in C++ so I'm assuming it's something about that that I'm not understanding.
The class Node has not any method named append so you get that error message:
tmp->next->append(data);
^^^^^^^^^^^^^
struct Node {
int data;
Node* next;
};
To append a node to a linked-list, you don't need an append method within Node. Remove that. Correct the append process in LinkedList::append:
void append(int data) {
Node* tmp = head;
while (tmp->next)
tmp = tmp->next;
tmp->next = new Node();
tmp->next->data = data;
tmp->next->next = nullptr;
}
I did't test, but you need something like above code. At first, it tries to access to the end of list. Then it appends a node.
Recursive implementation:
void append(int data) {
append(data, head);
}
void append(int data, Node *node) {
if (node->next)
append(data, node->next);
else {
tmp->next = new Node();
tmp->next->data = data;
tmp->next->next = nullptr;
}
}
Your append method isn't defined on the Struct Node. Instead it's defined on the LinkedList class so you need to invoke it accordingly. You can redefine the append method to take a node as a parameter or add an append method to the Struct Node itself. Also there's no need to assign the result of append to tmp =
Your append method is void.
tmp->next is a Node, so to call append function, you must declare it in Node struct
Like this
struct Node
{
void append(int data)
{
if (next)
next->append(data);
else
{
next = new Node();
next->data = data;
next->next= nullptr;
}
}
int data;
Node* next;
};
it's clear from the pseudo code next->append(data); that append is meant to be a member of Node.
Here's how you might use Node::append from LinkedList::append
class LinkedList {
void append(int data) {
if (head == nullptr) {
head = new Node();
head->data=data;
head->next=nullptr;
}
else {
head->append(data);
}
}
}
The node structure does not contain any append method.
Moreover, you are splitting work that can be done in one methos to two methods, writing more code.
See my answer to another question here with working code I wrote
https://stackoverflow.com/a/37358192/6341507
As you can see, I solve all in method
AddItem(int i)
I start seeing that creating linked list i kindof har for many people here, so I will further edit my answer there to provide additional information.
Good luck!

Eclipse complains about recursive function call

A simple binary search tree class declaration:
#include <vector>
#include <stdio.h>
// Provides various structures utilized by search algorithms.
// Represents an generalized node with integer value and a set of children.
class Node {
protected:
std::vector<Node*> children;
int value;
public:
//Creates a new instance of a Node with a default value=-1.
Node(){value = -1;}
//Creates a new instance of a Node with a specified value.
explicit Node(int value){this->value = value;}
virtual ~Node(){delete children;}
//Adds new Node with specified value to the list of child nodes. Multiple
//children with the same value are allowed.
//Returns added node.
virtual Node* Insert(int value);
//Removes first occurrence of a Node with specified value among children.
virtual void Remove(int value);
};
// Represents a binary search tree node with at most two children.
class BTNode: public Node {
public:
//Creates a new instance of a BTNode with a default value=-1.
BTNode():Node(){}
//Creates a new instance of a BTNode with a specified value.
explicit BTNode(int value):Node(value){}
//Adds new BTNode with specified value to the list of child nodes in an
//ordered manner, that is right child value is >= value of this node and
//left child value < value of this node.
virtual BTNode* Insert(int value);
//Removes first occurrence of a Node with specified value from the tree.
virtual void Remove(int value);
//Returns a node with specified value.
virtual BTNode* Search(int value);
};
And eclipse complains about it's definition:
BTNode* BTNode::Search(int value){
if (this->value == value) return *this;
//Determines whether value is in left(0) or right(1) child.
int child = this->value > value ? 0 : 1;
if (children[child] != NULL)
return children[child]->Search(value);
return NULL;
}
exactly where the call children[child]->Search(value) takes place with a message "method Search could not be resolved". Build runs just fine (no compilation errors whatsoever). What's the problem with that?
P.S.:Haven't tried running the code,yet. Working on it.
Search is part of the BTNode interface but it is not part of Nodes interface, children is a vector of Node* so it is not valid to call Search on a Node *. If it makes sense for Node to have a Search method then adding it to Node would fix that issue. If not then you need to rethink your design and that is probably beyond the scope of this question.
There are also a few other issues. You have:
virtual ~Node(){delete children;}
but children is not a pointer it is a std::vector<Node*>. You need to iterate over the vector and call delete each element. In Search you have this:
if (this->value == value) return *this;
but Search returns a BTNode* so it should be:
if (this->value == value) return this ;