BST.h
#include "stdafx.h"
#include <iostream>
#include <cstddef>
#include <string>
using namespace std;
#ifndef BST_H_
#define BST_H_
template <class bstdata>
class BST
{
private:
struct Node
{
bstdata data;
Node* left;
Node* right;
Node() : left(NULL), right(NULL){}
Node(bstdata newdata) : left(NULL), right(NULL), data(newdata){}
};
typedef struct Node* Nodeptr;
Nodeptr root;
int size;
/** Private Helper Functions **/
void addValue(Nodeptr root, bstdata value);
void printInOrder(Nodeptr root);
public:
BST();
bool isEmpty();
int getSize();
void add(bstdata value);
bstdata getRoot();
void inOrderPrint();
};
/**Public functions*/
template <class bstdata>
BST<bstdata>::BST() : size(0), root(NULL){};
template <class bstdata>
void BST<bstdata>::add(bstdata value)
{
if (root == NULL)
{
root = new Node(value);
size++;
}
else
addValue(root, value);
}
template <class bstdata>
void BST<bstdata>::addValue(Nodeptr root, bstdata value)
{
if (value == root->data)
return;
if (value < root->data)
{
if (root->left == NULL)
{
root->left = value;
size++;
}
}
else
addValue(root-> left, value);
if (root-> right == NULL)
{
root->left = value;
size++;
}
else
addValue(root-> right, value);
}
template <class bstdata>
bstdata BST<bstdata>::getRoot()
{
if (size == 0)
cout << "getRoot: there is no root in the BST" << endl;
else
return root->data;
}
#endif
BST.cpp
// BSTTest.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "BST.h"
#include <iostream>
#include <cstddef>
#include <string>
using namespace std;
int main()
{
BST<int> B;
B.add(5);
B.getRoot();
return 0;
}
So the error, the title of this post, I am getting happens twice. It is in the two lines that read: root->left = value; located in the addValue function in the header file. I am not sure why I can not assign the value to the pointer left. If anyone could help that could be great.
The lines
root->left = value;
and
root->left = value;
are not right. You cannot assign an object of type int
to an object of type Node*
.
They need to be
root->left = new Node(value);
and
root->left = new Node(value);
respectively.
Like your error says, the two types are incompatible. The template type is int
(first line in main) and the type of left
is Node*
. Do you mean to say root->data = value
? Either that or you need to create a new Node
, set its data
to value and then assign the new node to
root->left`.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.