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.