C++ Binary Search Tree Insertion Algorithm - c++

I am trying to finish a C++ project where I have to insert an array of integers into a binary search tree. I have to use a particular insertion algorithm:
insert(T, z)
1 y = NIL
2 x = T.root
3 while x != NIL
4 y = x
5 if z.key < x.key
6 x = x.left
7 else x = x.right
8 z.p = y
9 if y == NIL
10 T.root = z
11 else if z.key < y.key
12 y.left = z
13 else y.right = z
Here is my code so far:
main.cpp
#include <iostream>
#include "binarytree.h"
using namespace std;
int main()
{
BinaryTree tree;
int array [10] = {30, 10, 45, 38, 20, 50, 25, 33, 8, 12};
for (int i = 0; i < 10; i++)
{
tree.add(array[i]);
}
tree.inordertreewalk();
return 0;
}
void BinaryTree::insert(node *&T, node *&z)
{
node *y = nullptr;
y = new node;
y->key = 0;
y->left = y->right = y->parent = nullptr;
node *x = T;
while (x != nullptr)
{
y = x;
if (z->key < x->key)
x = x->left;
else
x = x->right;
}
z->parent = y;
if (y == nullptr)
T = z;
else if (z->key < y->key)
y->left = z;
else
y->right = z;
}
void BinaryTree::add(int num)
{
node *newNode = nullptr;
newNode = new node;
newNode->left = newNode->right = newNode->parent = nullptr;
newNode->key=num;
insert(root, newNode);
}
void BinaryTree::inordertreewalk(node *x) const
{
if (x)
{
inordertreewalk(x->left);
cout << x->key << endl;
inordertreewalk(x->right);
}
}
void BinaryTree::destroysubtree(node *newNode)
{
if (newNode)
{
if (newNode->left)
destroysubtree(newNode->left);
if (newNode->right)
destroysubtree(newNode->right);
delete newNode;
}
}
binarytree.h
#ifndef BINARYTREE_H_
#define BINARYTREE_H_
#include <iostream>
using namespace std;
class BinaryTree
{
private:
struct node
{
int key;
node* left;
node* right;
node* parent;
};
node *root;
void insert(node *&, node *&);
void inordertreewalk(node *) const;
void destroysubtree(node *);
public:
BinaryTree()
{ root = nullptr; }
~BinaryTree()
{ destroysubtree(root); }
void add(int);
void inordertreewalk() const
{ inordertreewalk(root); }
};
#endif
This program compiles, however it is not displaying the tree. I know that the problem is with my implementation of the insertion algorithm because I used a different algorithm I found in a textbook and kept the rest of the code the same and the tree was displayed in order. I know that T is a pointer to the root, but I'm not sure if the numbers are being correctly stored in the tree.
Thanks for your help.

Related

Trouble with pointers C++

Well, i'm tried to build something like Binary Search Tree. And after some iterations i'm creating newnode and it has pointer which has already used. How to solve this problem, without classes. For example test,
9
1
7
5
21
22
27
25
20
10
Build it in reverse order (last is root, first cnt of vertex)
Here code:
#include <bits/stdc++.h>
using namespace std;
const int N = 3000;
int n;
int a[N];
struct node {
int v;
node *left, *right;
};
vector<int> ans;
node qwe;
void add(node *root, int elem) {
if (elem > root->v) {
if (root->right != NULL) {
add(root->right, elem);
} else {
node newnode{};
newnode.v = elem;
newnode.right = NULL;
newnode.left = NULL;
node *lsls;
lsls = &newnode;
root->right = lsls;
}
} else {
if (root->left != NULL) {
add(root->left, elem);
} else {
node newnode;
newnode.v = elem;
newnode.right = NULL;
newnode.left = NULL;
node *lsls;
lsls = &newnode;
root->left = lsls;
}
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
cin >> n;
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
qwe.v = a[n - 1];
qwe.left = NULL;
qwe.right = NULL;
node *pointer;
pointer = &qwe;
for (int i = n - 2; i > -1; --i) {
add(pointer, a[i]);
}
pointer = &qwe;
return 0;
}

How to actually get the values to insert into this linked-list c++

So I wrote a function to have values insert into the linked list but now I'm having trouble successfully calling it from the main. Here's my code
class node
{
public:
int item; node* next;
node(int x, node* t)
{
item = x; next = t;
}
void insert(int n)
{
node *tmp = new node(n, next);
tmp -> item = n;
tmp->next = head;
head = tmp;
}
};
typedef node *link;
int main()
{
int i, N = 9, M = 5;
link t = new node(1, 0); t->next = t;
link x = t;
for (i = 2; i <= N; i++)
x = insert((x->next = new node(i, t)));
while (x != x->next)
{
for (i = 1; i < M; i++) x = x->next;
x->next = x->next->next;
}
cout << x->item << endl;
}
You could do it like this:
class Node
{
int item; Node* next;
public:
Node(int x, Node* t)
{
item = x; next = t;
}
int getItem() { return item; }
Node* getNext() { return next; }
void setNext(Node* n) { next = n; }
};
class List
{
Node *head = nullptr;
public:
void append(int n)
{
Node *tmp = new Node(n, head);
head = tmp;
}
Node* getHead() { return head; }
};
int main() {
int i, N = 9;
List list;
for (i = 1; i <= N; i++)
list.append(i);
Node* x = list.getHead();
// remove every second element
while (x != nullptr && x->getNext() != nullptr) {
Node* next = x->getNext();
x->setNext(next->getNext());
delete next;
x = x->getNext();
}
// print
x = list.getHead();
while (x != nullptr) {
std::cout << x->getItem() << std::endl;
x = x->getNext();
}
}
This way you have List in which you can insert. And Node which stores data.

C++ Binary Search Tree Implementation

I am working on a project in C++ in which I have to create a binary search tree that inserts items from an array. I have to use the following insert algorithm:
tree-insert(T, z)
y = NIL
x = T.root
while x != NIL
y = x
if z.key < x.key
x = x.left
else x = x.right
z.p = y
if y == NIL
T.root = z
else if z.key < y.key
y.left = z
else y.right = z
Here is what I have so far:
#include <iostream>
using namespace std;
struct node
{
int key;
node* left;
node* right;
node* p;
node* root;
};
void insert(node*, node*);
void printinorder(node*);
int main()
{
node *root;
node* tree = new node;
node* z = new node;
int array [10] = {30, 10, 45, 38, 20, 50, 25, 33, 8, 12};
for (int i = 0; i < 10; i++)
{
z->key = array[i];
insert(tree, z);
}
printinorder(tree);
return 0;
}
void insert(node *T, node *z)
{
node *y = nullptr;
node* x = new node;
x = T->root;
while (x != NULL)
{
y = x;
if (z->key < x->key)
x = x->left;
else
x = x->right;
}
z->p = y;
if (y == NULL)
T->root = z;
else if (z->key < y->key)
y->left = z;
else
y->right = z;
}
void printinorder(node *x)
{
if (x != NULL)
{
printinorder(x->left);
cout << x->key << endl;
printinorder(x->right);
}
}
This code compiles however when I run it, it seg faults. I believe the problem has something to do with the nodes I am creating or my function calls.
Thanks for your help.
Besides the issues noted in the comments, the biggest bug in this code is a lack of a constructor that initializes all pointers in a new node to NULL.
As such, every node you create will have its pointers containing random garbage. You code initializes some of them, but most are not. Trying to use uninitialized pointers will result in an immediate crash.
You need to fix all the problems that have been noted in the comments, and have a proper constructor for your node class.

C++ Singly Linked List Find Nodes value x spaces from beginning

float get(int x) {
if(x == 0) {return head->x;}
else {
Node *current = head;
for(int a=0; a<x; a++) {
current = current->next;
}
return current->x;
}
}
This is my code, but when I run it with a test case, it says "Lab3.exe has stopped working". I'm still really new to C++ and our teacher hasn't been helpful in the slightest, can anyone give me advice on my implementation?
EDIT:
Here's the test case...
#include <iostream>
#include <string>
using namespace std;
// including _my copy_ of SLList
#include "./SLList.h"
using namespace ods;
template <class FloatList>
bool listTest(){
FloatList L;
L.add(0, 3.14);
L.remove(0);
L.add(0, 1.62);
L.add(1, 2.23);
L.set(1, 2.72);
/*float x = L.get(1);*/
return ( 2.72f == L.get(1) and 2 == L.size() );
}
int main() {
if ( listTest<SLList<float> >() )
cout << "SLList passes basic list interface test" << endl;
else
cout << "SLList FAILS basic list interface test" << endl;
}
And here's how the SLL is set up:
template<class T>
class SLList {
T null;
protected:
class Node {
public:
T x;
Node *next;
Node(T x0) {
x = 0;
next = NULL;
}
};
Node *head;
Node *tail;
int n;
public:
SLList() {
null = (T)NULL;
n = 0;
head = tail = NULL;
}
virtual ~SLList() {
Node *u = head;
while (u != NULL) {
Node *w = u;
u = u->next;
delete w;
}
}

AVL Tree Sentinel

I am trying to finish a school project with AVL trees. What happens is that once I insert the root as well as two other nodes everything is ok, the program fails if I try adding any more than those three nodes. I figured that the problem was the newnode's pointers were not pointing to the sentinel NIL once they were created; I tried setting the newnode's pointers pointing to NIL, but no luck.
How can I fix this?
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <cmath>
#include <stdio.h>
#include "graphvisualize.h"
using namespace std;
typedef struct node Tnode;
Tnode *root;
Tnode *NIL;
Tnode *newnode;
void InitializeTree(int k) {
//initialize the list with the root node
NIL=(Tnode *)malloc(sizeof(Tnode));
root=(Tnode *)malloc(sizeof(Tnode));
//change to null later
root->value = k;
root->parent = NIL;
root->right = NIL;
root->left = NIL;
root->height = 1;
NIL->right = NULL;
NIL->left = NULL;
NIL->parent = NULL;
}
void insert(int v) {
Tnode *newnode=(Tnode *)malloc(sizeof(Tnode));
newnode->value = v;
Tnode *y = NIL;
Tnode *x = root;
while(x != NIL) {
y = x;
if(newnode->value < x->value) {
x = x->left;
} else {
x = x->right;
}
newnode->parent = y;
if(y == NIL) {
root = newnode;
} else if(newnode->value < y->value) {
y->left = newnode;
} else {
y->right = newnode;
}
cout << "insert ";
//Heres my problem
//trying to set right and left pointer to NIL
newnode->left = NIL;
newnode->right = NIL;
}
//height manager
int h = 1;
newnode->height = h;
while((newnode->parent != NIL) && (newnode->height >= newnode->parent->height)) {
newnode = newnode->parent;
newnode->height++;
}
cout << "height-fix ";
}
//Display AVL Tree
void ViewTree() {
ofstream AVLfile;
AVLfile.open("AVLgraphfile.dot");
AVLfile << visualize_tree(root);
AVLfile.close();
}
int main() {
InitializeTree(7);
cout << "root ";
insert(5);
insert(8);
//insert(6);
ViewTree();
return 0;
}