C++ AVL Tree balancing Issues - c++

I've built an AVL Tree out of an old Binary Tree in C++ for practice and it is not working correctly. I think it may not be updating the height of the nodes correctly but I can't figure out the root of the issue ( I'm 90% sure it has to do with the helper functions getHeight, setHeight, getBalance).
Some example test runs..:
adding 6,3,4 causes a Right Rotation it should cause a RL rotation
similarly adding 20,30,25 causes a LL rotation when it should cause a LR rotation
adding 20,30,10,5,6 causes two seperate Right rotations when it should cause a RL rotation
#include <string>
#include <sstream>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cstdlib>
using namespace std;
struct intNode {
int data;
intNode * Left;
intNode * Right;
int height;
intNode(int input, intNode * iLeft= NULL, intNode * iRight = NULL) {
data = input;
Left = iLeft;
Right = iRight;
height = 0;
}
};
int getHeight(intNode* temp) {
if (temp == NULL)
return 0;
return temp->height;
}
void setHeight(intNode * temp)
{
int hLeft = getHeight(temp->Left);
int hRight = getHeight(temp->Right);
temp->height = 1 + max(hLeft, hRight);
}
int getBalance(intNode * temp) {
if (temp == NULL) {
return 0;
} else {
return getHeight(temp->Left) - getHeight(temp->Right);
}
}
struct intTree {
intNode * root;
intTree();
void addNode(int input);
void addNode(int input, intNode *& root);
void print();
void print(intNode *input);
intNode * balanceTree(intNode *& sub);
intNode * rotateRight(intNode *& sub);
intNode * rotateLeft(intNode *& sub);
};
void intTree::print(intNode *input) {
if (input != NULL) {
print(input->Left);
cout << input->data << endl;
print(input->Right);
}
}
void intTree::print() {
print(root);
}
intNode * intTree::rotateRight(intNode *& subTree) {
intNode * newRoot = subTree->Left;
subTree->Left = newRoot->Right;
newRoot->Right = subTree;
setHeight(subTree);
setHeight(newRoot);
return newRoot;
}
intNode * intTree::rotateLeft(intNode *& subTree) {
intNode * newRoot = subTree->Right;
subTree->Right = newRoot->Left;
newRoot->Left = subTree;
setHeight(subTree);
setHeight(newRoot);
return newRoot;
}
intNode* intTree::balanceTree(intNode *& subTree) {
setHeight(subTree);
if (getBalance(subTree) == 2 && getBalance(subTree->Right) < 0) {
cout << "RL" << endl;
subTree->Left = rotateLeft(subTree->Left);
return rotateRight(subTree);
} else if (getBalance(subTree) == 2) { // RR
cout << "RR" << endl;
return rotateRight(subTree);
} else if (getBalance(subTree) == -2 && getBalance(subTree->Left) > 0) { // LR
cout << "LR" << endl;
subTree->Right = rotateRight(subTree->Right);
return rotateLeft(subTree);
} else if (getBalance(subTree) == -2) { // LL
cout << "LL" << endl;
return rotateLeft(subTree);
} else {
return subTree; // balanced
}
}
intTree::intTree() {
root = NULL;
}
void intTree::addNode(int input, intNode *& temp) {
if (temp == NULL) {
temp = new intNode(input);
} else if (input < temp->data) {
cout <<" added to the left" << endl;
addNode(input,temp->Left);
} else if (input > temp->data) {
cout <<" added to the right" << endl;
addNode(input, temp->Right);
}
temp = balanceTree(temp);
}
void intTree::addNode(int input) {
addNode(input, root);
}
void read() {
string num;
int balance, input;
int i = 0;
intTree * intBST = new intTree();
while (i != 10) {
cout << "number?" << endl;
cin >> input;
intNode *tempInt= new intNode(input);
intBST->addNode(input);
i++;
}
cout << "Finished reading in files" << endl;
while (true) {
string userInput;
cin >> userInput;
if (userInput == "Exit") {
cout << "Goodbye!" << endl;
return;
}
if (userInput == "Print") {
intBST->print();
return;
}
}
}
void main() {
read();
return 0;
}
I would appreciate any tips/help on further figuring this out. Let me know if I can provide any more information to help.
Thank you.

Related

Implementing a stack using a linked list and class templates

I'm trying to implement a stack using a linked list and class template. I'm not getting any compiler errors but my logic may be wrong, kind of lost. I had a working program in just a single file only using a struct so I had difficulties with translating it over using multiple files and template classes. I will also include my single file cpp below, hopefully it helps. Any help will be greatly appreciated. I have a header.h file, functions.cpp and main. cpp.
Header.h
#define STACK_H
#include <iostream>
using namespace std;
//to implement a stack using linked list
template<class T>
class node{
public:
T data;
node<T>*next;
};
template<class T>
class stack{
private:
node<T> *item;
node<T> *top;
public:
stack(); // constructor
void push( node<T> *); // to insert an item to the stack
void pop(); // to remove an item from the stack
void display(); // to display the stack elements on screen
node<T> *newnode(int );
};
#include "functions.cpp"
#endif
functions.cpp
#include <iostream>
#include "header.h"
#ifndef FUNCTIONS
#define FUNCTIONS
using namespace std;
template<class T>
stack <T> :: stack(){
node<T> *top = NULL;
}
template<class T>
void stack <T> :: push(node<T> * q){
if (top == NULL)
top = q;
else
{
q->next = top;
top = q;
}
}
template<class T>
void stack <T> :: pop(){
if (top == NULL) {
cout << "Stack is empty";
}
else {
cout << "Popped element is " << top->data;
item = top;
top = top->next;
delete(item);
}
}
template<class T>
void stack <T> :: display(){
node<T> *q;
q = top;
if (top == NULL) {
cout << "Stack is empty!!";
}
else {
while (q != NULL)
{
cout << q->data << " ";
q = q->next;
}
}
}
template<class T>
node<T> * stack <T> :: newnode(int x)
{
item = new node<T>;
item->data = x;
item->next = NULL;
return(item);
}
#endif
main.cpp
#include<iostream>
#include "header.h"
using namespace std;
int main()
{
int ch, x;
stack <int> myStack;
node<int> *nptr;
do
{
cout << "\n\n1.Push\n2.Pop\n3.Print Stack\n4.Exit";
cout << "\nPlease enter a function(1-4):";
cin >> ch;
if (ch == 1)
{
cout << "\nEnter data:";
cin >> x;
nptr = myStack.newnode(x);
myStack.push( nptr);
}
else if (ch == 2)
{
myStack.pop();
}
else if (ch == 3)
{
myStack.display();
}
else cout << "\nInvalid Entry";
} while (ch != 4);
return 0;
}
Single file working program
struct nodeType
{
int data;
nodeType *next;
};
nodeType *top = NULL;
nodeType *p;
nodeType* newnode(int x)
{
p = new nodeType;
p->data = x;
p->next = NULL;
return(p);
}
void push(nodeType *q)
{
if (top == NULL)
top = q;
else
{
q->next = top;
top = q;
}
}
void pop() {
if (top == NULL) {
cout << "Stack is empty";
}
else {
cout << "Popped element is " << top->data;
p = top;
top = top->next;
delete(p);
}
}
void printStack()
{
nodeType *q;
q = top;
if (top == NULL) {
cout << "Stack is empty!!";
}
else {
while (q != NULL)
{
cout << q->data << " ";
q = q->next;
}
}
}
int main()
{
int ch, x;
nodeType *nptr;
do
{
cout << "\n\n1.Push\n2.Pop\n3.Print Stack\n4.Exit";
cout << "\nPlease enter a function(1-4):";
cin >> ch;
if (ch == 1)
{
cout << "\nEnter data:";
cin >> x;
nptr = newnode(x);
push(nptr);
}
else if (ch == 2)
{
pop();
}
else if (ch == 3)
{
printStack();
}
else cout << "\nInvalid Entry";
} while (ch != 4);
return 0;
}

Issues printing binary tree using breadth-first traversal in C++?

I'm writing a program that converts an expression in prefix notation to an expression tree. I'm having trouble getting the correct problem and I believe something is wrong with my print function which uses breadth first traversal. For example, when I input +-*1234, I get the output below. However, the 1 and the 2 should be the first two nodes in Depth 3. Could anybody point me in the right direction or explain what is happening?
Output:
Enter a prefix expression: +-*1234
Depth 0: +
Depth 1: - 4
Depth 2: * 3 1 2
Depth 3: [Empty][Empty][Empty][Empty][Empty][Empty][Empty][Empty]
My program:
#include <iostream> // For cout, cin
#include <cctype> // For isdigit
#include <queue> // For queue, push, pop, front
#include <algorithm> // For max
using namespace std;
class node {
public:
// CONSTRUCTOR
node(char data);
char data;
node *left, *right;
};
node::node(char data)
{
this -> data = data;
this -> left = NULL;
this -> right = NULL;
}
class next_node {
public:
// CONSTRUCTOR
next_node(node *tree_node);
node *tree_node;
next_node *next;
};
next_node::next_node(node *tree_node)
{
this->tree_node = tree_node;
next = NULL;
}
class tree {
public:
// CONSTRUCTOR
tree() { root = NULL; }
// Member Functions
void add_node(node *ptr);
void insert(char data);
void build(string prefix);
void print();
int get_height(node *ptr);
int double_num(int n);
bool isOperator(char sym);
node *remove_node()
{
if (root != NULL) {
node *ptr = root -> tree_node;
root = root -> next;
return ptr;
}
}
node *get_root()
{
return (root -> tree_node);
}
private:
next_node *root;
};
void tree::add_node(node *ptr)
{
if (root == NULL) root = new next_node(ptr);
else {
next_node *new_ptr = new next_node(ptr);
new_ptr -> next = root;
root = new_ptr;
}
}
void tree::insert(char data)
{
// If number
if(isdigit(data)) {
node *new_ptr = new node(data);
add_node(new_ptr);
// If operator
} else if (isOperator(data)) {
node *new_ptr = new node(data);
new_ptr -> left = remove_node();
new_ptr -> right = remove_node();
add_node(new_ptr);
}
}
void tree::build(string prefix)
{
// Scan from right to left
for (int i = prefix.length() - 1; i >= 0 ; i--) {
insert(prefix[i]);
}
}
void tree::print()
{
queue<node*> values;
node * root_ptr = get_root();
queue<char> line;
if (root_ptr) values.push(root_ptr);
else {
values.push(NULL);
}
while (!values.empty())
{
node * current_node = values.front();
values.pop();
line.push(current_node -> data);
if (current_node -> left) {
values.push(current_node -> left);
}
if (current_node -> right) {
values.push(current_node -> right);
}
}
for(int i=0; i < get_height(root_ptr); i++) {
cout << "Depth " << i << ": ";
for(int j=0; j < double_num(i); j++) {
if (!line.empty()) {
if (line.front() == NULL) {
cout<< "Empty";
} else {
cout << line.front() << " ";
line.pop();
}
} else if (line.empty()) {
cout << "[Empty]";
}
}
cout << "\n";
}
}
int tree::get_height(node *ptr) {
if(ptr == NULL ) return 0;
else {
return (1 + max(get_height(ptr -> left),
get_height(ptr -> right)));
}
}
int tree::double_num(int n){
if (n == 0) {
return 1;
} else {
return 2 * double_num(n - 1);
}
}
bool tree::isOperator(char sym)
{
return ( sym == '+' ||
sym == '-' ||
sym == '*' ||
sym == '/' ||
sym == '^' ||
sym == '(' ||
sym == ')' );
}
int main()
{
string user_input;
tree expr_tree;
cout << "Enter a prefix expression: ";
cin >> user_input;
// Build binary tree and print result
expr_tree.build(user_input);
expr_tree.print();
return 0;
}`

A ton of undefined reference errors

I don't know if I'm linking wrong but I'm compiling this on linux and I'm getting a LOT of undefined references for my node functions. I'm writing a binary search tree to searches for telephones for class that is due tonight.
bst.cpp
#include "bst.hpp"
BST::BST(void)
{
count = 0;
root = NULL;
}
void BST::insert(long long x, string y)
{
Node *newnode = new Node(x, y);
Node *temp;
if (count == 0)
{
root = newnode;
count++;
}
else
{
while(temp->getleft() != NULL && temp->getright() != NULL)
{
if(newnode->getnum() < temp->getnum())
{
temp = temp->getleft();
}
else
{
temp = temp->getright();
}
}
if (newnode->getnum() < temp->getnum())
{
temp->setleft(newnode);
}
else
{
temp->setright(newnode);
}
}
}
Node * BST::getroot(void)
{
return root;
}
Node* BST::delete_node(Node *troot, long long key)
{
if (count == 0)
{
return troot;
}
else if(key < troot->getnum())
{
delete_node(troot->getleft(), key);
}
else if (key > troot->getnum())
{
delete_node(troot->getright(), key);
}
else
{
if(troot->getleft() == NULL && troot->getright() == NULL)
{
delete troot;
troot == NULL;
}
else if(troot->getright() == NULL)
{
Node *temp = troot;
troot = troot->getleft();
delete temp;
}
else if(troot->getleft() == NULL)
{
Node *temp = troot;
troot = troot->getright();
delete temp;
}
}
return troot;
}
void BST::preverse(Node* troot)
{
if(root == NULL)
{
cout << "The tree is empty\n";
}
if(troot == NULL)
{
return;
}
cout << troot->getname() << endl;
cout << troot->getnum() << endl;
preverse(troot->getleft());
preverse(troot->getright());
}
void BST::postverse(Node* troot)
{
if(root == NULL)
{
cout << "The tree is empty\n";
}
if(troot == NULL)
{
return;
}
postverse(troot->getleft());
postverse(troot->getright());
cout << troot->getname() << endl;
cout << troot->getnum() << endl;
}
void BST::inverse(Node* troot)
{
if(root == NULL)
{
cout << "The tree is empty\n";
}
if(troot == NULL)
{
return;
}
inverse(troot->getleft());
cout << troot->getname() << endl;
cout << troot->getnum() << endl;
inverse(troot->getright());
}
void BST::search(Node* troot, long long key)
{
if(root == NULL)
{
cout << "The tree is empty\n";
}
if(troot == NULL)
{
return;
}
if(key == troot->getnum())
{
cout << troot->getname();
}
search(troot->getleft(), key);
search(troot->getright(), key);
}
bst.hpp
#include "node.hpp"
#ifndef bst_hpp
#define bst_hpp
class BST
{
Node* root;
long long count;
public:
BST(void);
void insert(long long x, string y);
Node* getroot(void);
Node* delete_node(Node* troot, long long key);
void preverse(Node* troot);
void postverse(Node* troot);
void inverse(Node* troot);
void search(Node* troot, long long key);
};
#endif
node.cpp
#include "node.hpp"
Node::Node(void)
{
number = 0;
name = "no name";
left = NULL;
right = NULL;
}
Node::Node(long long t, string n)
{
number = t;
name = n;
left = NULL;
right = NULL;
}
Node * Node::getleft(void)
{
return left;
}
Node * Node::getright(void)
{
return right;
}
void Node::setleft(Node * ptr)
{
left = ptr;
}
void Node::setright(Node * ptr)
{
right = ptr;
}
long long Node::getnum(void)
{
return number;
}
string Node::getname(void)
{
return name;
}
node.hpp
#ifndef node_hpp
#define node_hpp
#include <string>
#include <iostream>
using namespace std;
class Node
{
long long number;
string name;
Node *left;
Node *right;
public:
Node(void);
Node(long long t, string n);
Node* getleft(void);
Node* getright(void);
void setleft(Node* ptr);
void setright(Node* ptr);
long long getnum(void);
string getname(void);
};
#endif
main.cpp
#include "bst.hpp"
using namespace std;
int main(void)
{
int choice;
long long numin;
string input;
BST phbook;
do
{
cout << "1. Insert a name and number.\n2. Delete using number.\n3. Traverse pre-order\n4. Traverse post-order\n";
cout << "5. Traverse in-order\n6. Search using number.\n6. Exit program\n";
switch(choice)
{
case 1:
cout << "Enter a name\n";
cin.ignore();
getline(cin, input);
cout << "Enter a number\n";
cin >> numin;
phbook.insert(numin, input);
break;
case 2:
cout << "Enter the phone number you'd like to delete.\n";
cin >> numin;
phbook.delete_node(phbook.getroot(), numin);
break;
case 3:
phbook.preverse(phbook.getroot());
break;
case 4:
phbook.postverse(phbook.getroot());
break;
case 5:
phbook.inverse(phbook.getroot());
break;
case 6:
cout << "Enter a phone number to search.\n";
cin >> numin;
phbook.search(phbook.getroot(),numin);
default:
numin=numin;
}
}while(choice >= 1 && choice <= 6);
return 0;
}
To me, nothing looks wrong in linking the files.
Some examples : undefined reference to Node::getnum()
undefined reference to Node::getname()
Check the order of compiled elements:
g++ node.cpp -o node.o bst.cpp -o bst.o main.cpp -o main.o
Result:
./main.o
1. Insert a name and number.
2. Delete using number.
3. Traverse pre-order
4. Traverse post-order
5. Traverse in-order
6. Search using number.
6. Exit program

Output of c++ program not coming as expected

I have made a C++ program for a binary tree. But the terminal is not asking the statement for inputting the direction for where the elements are to be placed.
Also when I replace the statement from " node *temp = new node " to "node *temp=NULL" the program stops working .
#include <iostream>
#include <cstring>
using namespace std;
class node {
int data;
node * left;
node * right;
public:
node * level_order(node * first);
node * create_bt(node * first);
void display(node * first);
};
//node *first=NULL;
node * node::create_bt(node * first) {
node * temp = new node;
int ele;
//char dir;
cout << "\n Enter data ";
cin >> ele;
temp->data = ele;
temp->left = NULL;
temp->right = NULL;
if (first == NULL) {
temp = first;
return first;
} else {
char dir[20];
cout << "\n Enter the direction ";
cin >> dir;
node * cur = first;
int j = 0;
while (dir[j] != '\0') {
if (dir[j] == 'l') {
cur = cur->left;
}
if (dir[j] == 'r') {
cur = cur->right;
}
j++;
}
cur = temp;
return first;
}
}
void node::display(node * first) {
if (first == NULL)
return;
cout << "\n " << first->data;
display(first->left);
display(first->right);
}
int main() {
int n;
node s;
node * first = NULL;
cout << "\n No of elements ";
cin >> n;
for (int i = 0; i < n; i++) {
first = s.create_bt(first);
}
s.display(first);
return 0;
}
first=s.create_bt(first); does not changes state, from NULL to 'l' or 'r'. You have to change that.
node*node::create_bt(node *first)
{
node *temp=new node;
int ele;
//char dir;
cout<<"\n Enter data ";
cin>>ele;
temp->data=ele;
temp->left=NULL;
temp->right=NULL;
char dir[20];
cout<<"\n Enter the direction ";
cin>>dir;
if(first==NULL)
{
temp=first;
return first;
}
else
{
node*cur=first;
int j=0;
while(dir[j]!='\0')
{
if(dir[j]=='l')
{
cur=cur->left;
}
if(dir[j]=='r')
{
cur=cur->right;
}
j++;
}
cur=temp;
return first;
}
}
I believe you re looking something like this. This is a basic binary tree, i had to make a basic one in order to understand how it works and how it chooses left and right. I make a class inside a class, in order to have access to my data members (node class, int data, *left , *right) and have them at the same time protected, all-in-one. As you can see "newnode" just creates a node and NULL s the pointers. Thats it. "Find" searches and finds a node with a current key, and returns it when exits. All the rest, i guess, you can understand them, as they are prety much the same with your code. The only thing you have to do is to define, when you want to direct the node you want. REMINDER: You have to find a way to utilize it, so the leafs will not end far-left or far-right.("Enter the direction"). I hope i helped you understand.
#include <iostream>
#include <conio.h>
using namespace std;
class mybTree {
class node {
public:
int data;
node * left;
node *right;
};
node *root;
node *newnode(int num){
node *newnode1;
newnode1 = new (nothrow) node;
newnode1->data = num;
newnode1->left = NULL;
newnode1->right = NULL;
return newnode1;
}
public:
node *find (int key) {
node *current;
current = root;
while (current->data !=key){
if (key<current->data){
current = current->left;
} else {
current = current->right;
}
if (current == NULL){
return NULL;
}
}
return NULL;
}
void display (node *ptr);
void display_tree();
bool insert(int num);
void post_order_delete(node *ptr);
mybTree();
~mybTree();
};
int main(){
char ch = ' ';
int a;
mybTree mybTree1;
while (ch !='0'){
cout << "0->Exit"<<endl<< "1-> add"<<endl<< "2-> find" <<endl<<"3-> Show me the tree\n";
ch = getch();
switch (ch) {
case '0':
break;
case '1':
cout << "number";
cin >> a;
if (!mybTree1.insert(a)){
cout << "Not enough memory" << endl;
}
break;
case '2' :
cout << "Number:" ;
cin >> a;
if (mybTree1.find(a)!=NULL) {
cout << "Found" << endl;
} else {
cout << "Not existed" << endl;
}
break;
case '3':
mybTree1.display_tree();
cout<<endl;
break;
default:
cout << "Wrong Message";
break;
}
}
return 0;
}
void mybTree::display(node *ptr) {
if (ptr == NULL){
return;
}
display(ptr->left);
cout << ptr->data<<endl;
display(ptr->right);
}
void mybTree::display_tree() {
//Displays the Tree
display(root);
}
bool mybTree::insert(int num) {
//It inserts a node. Desides left or right.
node *next,*current,*ptr;
int isleft;
next = current = root;
ptr = newnode(num);
if (ptr == NULL) {
return false;
}
if (root == NULL) {
root = ptr;
return true;
}
while (1){
if (num < current->data){
next = current->left;
isleft = 1;
} else {
next = current->right;
isleft = 0;
}
if (next == NULL){
if (isleft){
current->left = ptr;
} else {
current->right = ptr;
}
return true;
}
current=next;
}
return false;
}
void mybTree::post_order_delete(node *ptr) {
//deletes the node. Usefull for destructor
if (ptr == NULL){
return;
}
post_order_delete(ptr->left);
post_order_delete(ptr->right);
cout << ptr->data;
delete ptr;
}
mybTree::mybTree() {
//Constructor
root = NULL;
}
mybTree::~mybTree() {
//Destructor
post_order_delete(root);
root = NULL;
}

Priority Queue that utilizes BST -- DeleteLargest doesn't work

I am creating a priority queue that utilizes a binary search tree for my Data Structures class. But when I attempt to output the queue I always get 0. I have looked over my DeleteLargest and Dequeue member function but I can't find the mistake
Test.cpp
#include <iostream>
#include "CTree.h"
#include "PriorityQueueBST.h"
using namespace std;
int main()
{
int num, input, output;
cout << "Enter number of elements: ";
cin >> num;
PriorityQueueBST p;
for (int x = 0; x < num; x++)
{
cout << "Enter number " << x + 1
<< " of " << num << ": ";
cin >> input;
p.Enqueue(input);
}
for (int y = 0; y < num; y++)
{
cout << "Outputting number " << y + 1
<< " of " << num << ": ";
if(p.IsEmpty())
{
break; //we are done (this is an error!)
}
output = p.Dequeue();
cout << output << endl;
}
system("pause");
return 0;
//CTree* tr = new CTree();
//
//for (int i = 0; i < 3; i++)
// tr->Add();
//tr->View();
//system("pause");
//return 0;
}
BST Declaration file
//#ifndef CTREE_H
//#define CTREE_H
//using namespace std;
struct TreeNode
{
int info;
TreeNode* leftLink;
TreeNode* rightLink;
};
class CTree
{
private:
void AddItem( TreeNode*&, TreeNode*);
void DisplayTree(TreeNode*);
void Retrieve(TreeNode*&, TreeNode*,bool&);
void Destroy(TreeNode*&);
public:
CTree();
~CTree();
void Add();
void View();
bool IsEmpty();
int DeleteLargest(TreeNode*&);
TreeNode *tree;
};
//#endif
BST Implementation file
#include <iostream>
#include <string>
using namespace std;
#include "CTree.h"
CTree::CTree()
{
tree = NULL;
}
CTree::~CTree()
{
Destroy(tree);
}
void CTree::Destroy(TreeNode*& tree)
{
if (tree != NULL)
{
Destroy(tree->leftLink);
Destroy(tree->rightLink);
delete tree;
}
}
bool CTree::IsEmpty()
{
if(tree == NULL)
{
return true;
}
else
{
return false;
}
}
void CTree::Add()
{
TreeNode* newPerson = new TreeNode();
/*cout << "Enter the person's name: ";
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cin.getline(newPerson->name, 20);*/
/* cout << "Enter the person's contribution: ";
cin >> newPerson->info;*/
/*bool found = false;*/
newPerson->leftLink = NULL;
newPerson->rightLink = NULL;
/*Retrieve(tree, newPerson, found);
if (found)
cout << "info allready entered\n";
else*/
AddItem(tree, newPerson);
}
void CTree::View()
{
if (IsEmpty())
{
cout<<"The list is empy";
}
else
{
DisplayTree(tree);
}
};
void CTree::AddItem( TreeNode*& ptr, TreeNode* newPer )
{
if (ptr == NULL)
{
ptr = newPer;
}
else if ( newPer->info < ptr->info)
AddItem(ptr->leftLink, newPer);
else
AddItem(ptr->rightLink, newPer);
}
void CTree::DisplayTree(TreeNode* ptr)
{
if (ptr == NULL)
return;
DisplayTree(ptr->rightLink);
cout << ptr->info << endl; //cout<<ptr->name<<" "<<"$"<<ptr->info <<endl;
DisplayTree(ptr->leftLink);
}
void CTree::Retrieve(TreeNode*& ptr, TreeNode* newPer, bool& found)
{
{
if (ptr == NULL)
{
found = false; // item is not found.
}
else if ( newPer->info < ptr->info)
{
Retrieve(ptr->leftLink, newPer, found);
}
// Search left subtree.
else if (newPer->info > ptr->info)
{
Retrieve(ptr->rightLink, newPer, found);// Search right subtree.
}
else
{
//newPer.info = ptr->info; // item is found.
found = true;
}
}
}
int CTree::DeleteLargest(TreeNode*& tr)
{
int largest = 0;;
TreeNode* prev;
TreeNode* cur;
prev = NULL;
cur = tr;
if (tr == NULL)
{
cout << "The tree is empty"<<endl;
}
else if (tr->rightLink == NULL)
{
largest = tr->info;
}
else
{
prev = tr;
tr = tr->rightLink;
DeleteLargest(tr);
}
return largest;
}
Priority Queue Declaration
//#include <iostream>
//using namespace std;
//#include "SortedLinkedList.h"
#ifndef PRIORITYQUEUESLL__H
#define PRIORITYQUEUESLL__H
class PriorityQueueBST
{
public:
PriorityQueueBST();
~PriorityQueueBST();
void Enqueue(int);
int Dequeue();
bool IsEmpty();
private:
CTree* ourTree;
//sslNode* head;
};
#endif
Priority Queue Implementation
#include <iostream>
using namespace std;
#include "CTree.h"
#include "PriorityQueueBST.h"
PriorityQueueBST::PriorityQueueBST()
{
ourTree = new CTree();
//head = NULL;
}
PriorityQueueBST::~PriorityQueueBST()
{
}
void PriorityQueueBST::Enqueue(int dataToEnter)
{
ourTree->Add();
}
int PriorityQueueBST::Dequeue()
{
//check for empty??
return ourTree->DeleteLargest(ourTree->tree);
}
bool PriorityQueueBST::IsEmpty()
{
return ourTree->IsEmpty();
}
Your output is always 0 because in
int CTree::DeleteLargest(TreeNode*& tr)
{
int largest = 0;;
TreeNode* prev;
TreeNode* cur;
prev = NULL;
cur = tr;
if (tr == NULL)
{
cout << "The tree is empty"<<endl;
}
else if (tr->rightLink == NULL)
{
largest = tr->info;
}
else
{
prev = tr;
tr = tr->rightLink;
DeleteLargest(tr);
}
return largest;
}
you only set largest to something potentially != 0 if tr->rightlink is NULL. Otherwise you recur and set the largest variable local to another invocation of the function. That change is lost when the recursion goes up again, and in the topmost invocation, largest is still 0.
In the last line of the else branch, you should either
largest = DeleteLargest(tr);
or
return DeleteLargest(tr);
Another problem is that, despite its name, deleteLargest doesn't actually delete anything, so with the above, you would still always get the same value.