Determine the height of a binary tree - height

I have written a code to create and display a binary tree. This program worked and satisfied the requirements of the course I was on, however afterwards I attempted to add to the working program to find the height of the tree and so far with no luck. I have looked at many examples and none of the additions or changes I have made to my program made it work.
#include <cstdlib>
#include <iostream>
#include <cstdio>
using namespace std;
class TreeNode
{ public:
TreeNode *pLeft;
int data;
TreeNode *pRight;
TreeNode *leftHeight;
TreeNode *rightHeight;
TreeNode(int num)
{
data = num;
pLeft = NULL;
pRight = NULL;
}
}; ////////////////////////////////////////////
class Binary_Tree
{ private:
//int getHeight;
public:
TreeNode *rootPtr;
Binary_Tree()
{ rootPtr = NULL;
}
/* ---------------------------------- */
void Insert(int value)
{
TreeNode *pNewNode = new TreeNode(value);
TreeNode *pCurrent;
TreeNode *pPrevious;
pPrevious = NULL;
pCurrent = rootPtr;
while(pCurrent != NULL)
{ pPrevious = pCurrent;
if (value < (pPrevious -> data))
pCurrent = pCurrent -> pLeft;
else
pCurrent = pCurrent -> pRight;
}
if(pPrevious == NULL)
{ rootPtr = pNewNode;
}
else
{ if (value < (pPrevious -> data))
{ pPrevious -> pLeft = pNewNode;
pNewNode -> pLeft = pCurrent;
}
else
{ pPrevious -> pRight = pNewNode;
pNewNode -> pRight = pCurrent;
}
}
}
/* ------------------------------------------- */
int getHeight(TreeNode *TreePtr)
{
if( TreePtr == NULL)
{
return(0);
}
else
{
leftHeight = getHeight(r->pLeft);
rightHeight = getHeight(r->pRight);
if(leftHeight > rightHeight)
{
return(leftHeight + 1);
}
else
{
return(rightHeight + 1);
}
}
}
/* ------------------------------------------- */
void Display(TreeNode *TreePtr, int count)
{
if(TreePtr !=NULL)
{
count++;
Display(TreePtr -> pRight, count);
for(int i = i; i < count; i++)
{
printf(" ");
}
printf("%d \n", TreePtr -> data);
Display(TreePtr -> pLeft, count);
}
}//////////////////////end display //////////////////////
void DisplayInOrder(TreeNode *TreePtr)
{
if(TreePtr != NULL)
{
DisplayInOrder(TreePtr -> pLeft);
cout << TreePtr -> data << endl;
DisplayInOrder(TreePtr -> pRight);
}
}
};
/* -------------------------------------- */
/////////////////////////////////////////////////////////////
int main()
{ int number[8] = {7, 9, 3, 2, 12, 5, 8};
Binary_Tree Tree;
for (int i = 0; i <8; i++)
{
cout << "data inserted = "<< number[i] << endl;
Tree.Insert(number[i]);
}
cout << endl << "Display Tree" << endl << endl;
Tree.Display(Tree.rootPtr, 0);
cout << endl;
cout << endl << "tree height" << endl << endl;
getHeight(root);
cout << endl;
Tree.DisplayInOrder(Tree.rootPtr);
system("PAUSE");
return EXIT_SUCCESS;
}

There were compilation problems. After fixing them it seems to print the height. Note the "final height" line with the value 4
#include <cstdlib>
#include <iostream>
#include <cstdio>
using namespace std;
class TreeNode
{ public:
TreeNode *pLeft;
int data;
TreeNode *pRight;
TreeNode *leftHeight;
TreeNode *rightHeight;
TreeNode(int num)
{
data = num;
pLeft = NULL;
pRight = NULL;
}
}; ////////////////////////////////////////////
class Binary_Tree
{ private:
//int getHeight;
public:
TreeNode *rootPtr;
Binary_Tree()
{ rootPtr = NULL;
}
/* ---------------------------------- */
void Insert(int value)
{
TreeNode *pNewNode = new TreeNode(value);
TreeNode *pCurrent;
TreeNode *pPrevious;
pPrevious = NULL;
pCurrent = rootPtr;
while(pCurrent != NULL)
{ pPrevious = pCurrent;
if (value < (pPrevious -> data))
pCurrent = pCurrent -> pLeft;
else
pCurrent = pCurrent -> pRight;
}
if(pPrevious == NULL)
{ rootPtr = pNewNode;
}
else
{ if (value < (pPrevious -> data))
{ pPrevious -> pLeft = pNewNode;
pNewNode -> pLeft = pCurrent;
}
else
{ pPrevious -> pRight = pNewNode;
pNewNode -> pRight = pCurrent;
}
}
}
/* ------------------------------------------- */
int getHeight(TreeNode *TreePtr)
{
if( TreePtr == NULL)
{
return(0);
}
else
{
int leftHeight = getHeight(TreePtr->pLeft);
int rightHeight = getHeight(TreePtr->pRight);
if(leftHeight > rightHeight)
{
return(leftHeight + 1);
}
else
{
return(rightHeight + 1);
}
}
}
/* ------------------------------------------- */
void Display(TreeNode *TreePtr, int count)
{
if(TreePtr !=NULL)
{
count++;
Display(TreePtr -> pRight, count);
for(int i = i; i < count; i++)
{
printf(" ");
}
printf("%d \n", TreePtr -> data);
Display(TreePtr -> pLeft, count);
}
}//////////////////////end display //////////////////////
void DisplayInOrder(TreeNode *TreePtr)
{
if(TreePtr != NULL)
{
DisplayInOrder(TreePtr -> pLeft);
cout << TreePtr -> data << endl;
DisplayInOrder(TreePtr -> pRight);
}
}
};
/* -------------------------------------- */
/////////////////////////////////////////////////////////////
int main()
{ int number[8] = {7, 9, 3, 2, 12, 5, 8};
Binary_Tree Tree;
for (int i = 0; i <8; i++)
{
cout << "data inserted = "<< number[i] << endl;
Tree.Insert(number[i]);
}
cout << endl << "Display Tree" << endl << endl;
Tree.Display(Tree.rootPtr, 0);
cout << endl;
cout << endl << "tree height" << endl << endl;
int height = Tree.getHeight(Tree.rootPtr);
cout << endl;
cout << "final height: " << height << endl;
Tree.DisplayInOrder(Tree.rootPtr);
system("PAUSE");
return EXIT_SUCCESS;
}

you have some errors in your code:
you are using r where it should be TreePtr
you did not declared root, i guess u wanted to use Tree
leftHeight and rightHeight needed to be declared
the declaration of getHeight is inside the class so you need to call Tree.getHeight. btw, this method should not be in the class or should not get a tree node.
here is the fixed code:
#include <cstdlib>
#include <iostream>
#include <cstdio>
using namespace std;
class TreeNode
{ public:
TreeNode *pLeft;
int data;
TreeNode *pRight;
TreeNode *leftHeight;
TreeNode *rightHeight;
TreeNode(int num)
{
data = num;
pLeft = NULL;
pRight = NULL;
}
}; ////////////////////////////////////////////
class Binary_Tree
{ private:
//int getHeight;
public:
TreeNode *rootPtr;
Binary_Tree()
{ rootPtr = NULL;
}
/* ---------------------------------- */
void Insert(int value)
{
TreeNode *pNewNode = new TreeNode(value);
TreeNode *pCurrent;
TreeNode *pPrevious;
pPrevious = NULL;
pCurrent = rootPtr;
while(pCurrent != NULL)
{ pPrevious = pCurrent;
if (value < (pPrevious -> data))
pCurrent = pCurrent -> pLeft;
else
pCurrent = pCurrent -> pRight;
}
if(pPrevious == NULL)
{ rootPtr = pNewNode;
}
else
{ if (value < (pPrevious -> data))
{ pPrevious -> pLeft = pNewNode;
pNewNode -> pLeft = pCurrent;
}
else
{ pPrevious -> pRight = pNewNode;
pNewNode -> pRight = pCurrent;
}
}
}
/* ------------------------------------------- */
int getHeight(TreeNode *TreePtr)
{
if( TreePtr == NULL)
{
return(0);
}
else
{
int leftHeight = getHeight(TreePtr->pLeft);
int rightHeight = getHeight(TreePtr->pRight);
if(leftHeight > rightHeight)
{
return(leftHeight + 1);
}
else
{
return(rightHeight + 1);
}
}
}
/* ------------------------------------------- */
void Display(TreeNode *TreePtr, int count)
{
if(TreePtr !=NULL)
{
count++;
Display(TreePtr -> pRight, count);
for(int i = i; i < count; i++)
{
printf(" ");
}
printf("%d \n", TreePtr -> data);
Display(TreePtr -> pLeft, count);
}
}//////////////////////end display //////////////////////
void DisplayInOrder(TreeNode *TreePtr)
{
if(TreePtr != NULL)
{
DisplayInOrder(TreePtr -> pLeft);
cout << TreePtr -> data << endl;
DisplayInOrder(TreePtr -> pRight);
}
}
};
/* -------------------------------------- */
/////////////////////////////////////////////////////////////
int main()
{ int number[8] = {7, 9, 3, 2, 12, 5, 8};
Binary_Tree Tree;
for (int i = 0; i <8; i++)
{
cout << "data inserted = "<< number[i] << endl;
Tree.Insert(number[i]);
}
cout << endl << "Display Tree" << endl << endl;
Tree.Display(Tree.rootPtr, 0);
cout << endl;
cout << endl << "tree height" << endl << endl;
cout << Tree.getHeight(Tree.rootPtr) << endl;
cout << endl;
Tree.DisplayInOrder(Tree.rootPtr);
system("PAUSE");
return EXIT_SUCCESS;
}

Related

C++ Red-Black Tree Left-Rotate error

Hello I am trying to create a Red-Black Tree in c++, The problem is on the left_rotate method. I print the tree in order using recursive method and included some extra std::cout to see what is going on. The problem is that when i insert values to the tree from 1-8, the root should be the number 4. Instead the root stucks at number 2 for some reason, when i try it the other way around from 10-1 the right_rotate method works like a charm. I have also added some cout to see where is the iterator going after fixing 1 violation. It goes to the right Path. when 8 number is inserted it recolors, then goes up to number 6 where it should perform a left_rotate but it doesnt for some reason.... here is the code
p.s : please forgive my english :)
struct Node
{
int value;
bool isBlack;
bool isLeft;
Node *parent, *left, *right;
};
class RBtree
{
private:
Node *root;
protected:
void inorder(Node *t)
{
if (t == nullptr)
return;
inorder(t->left);
if (t == root)
cout << "ROOT: \n";
cout << "value: " << t->value << " color: ";
if (t->isBlack)
cout << " B \n";
else
cout << " R \n";
if (!t->isLeft)
{
cout << "ITS A RIGHT CHILD \n";
}
else
{
cout << "ITS A LEFT CHILD \n";
}
if (t->parent)
cout << "PARENT: " << t->parent->value << "\n";
else
cout << "NONE\n";
if (t->left)
cout << "LEFT CHILD IS: " << t->left->value << "\n";
else
cout << "LEFT CHILD IS NULL \n";
if (t->right)
cout << "RIGHT CHILD IS: " << t->right->value << "\n\n";
else
{
cout << "RIGHT CHILD IS NULL \n\n";
}
cout << "--------------------- \n\n";
inorder(t->right);
}
void fix_violations(Node *);
void recolor(Node *t);
void left_rotate(Node *);
void right_rotate(Node *);
public:
RBtree()
{
root = nullptr;
}
void insert(int);
void remove(int);
void print_inorder()
{
inorder(root);
}
};
void RBtree::insert(int v)
{
Node * t = new Node(); // temp node
t->value = v;
t->isBlack = false;
t->isLeft = false;
t->parent = nullptr;
t->left = nullptr;
t->right = nullptr;
if (root == nullptr)
{
root = t;
root->isBlack = true;
return;
}
Node *it = root; // create iterator to root
while (it)
{
if (v < it->value)
{
if (!it->left)
{
it->left = t;
t->parent = it;
t->isLeft = true;
//cout << "inserted ";
break;
}
it = it->left;
}
else if (v > it->value)
{
if (!it->right)
{
it->right = t;
t->parent = it;
t->isLeft = false;
//cout << "inserted ";
break;
}
it = it->right;
}
else
{
break;
}
}
fix_violations(t);
}
// check violations method
void RBtree::fix_violations(Node *t)
{
cout << "Iterated on: ";
while (t != root)
{
cout << t->value << " ";
if (!t->parent || !t->parent->parent)
{
break;
}
if (!t->isBlack && !t->parent->isBlack)
{
bool u_isBlack = true;
if (!t->isLeft)
{
if (t->parent->parent->left)
u_isBlack = t->parent->parent->left->isBlack;
}
else
{
if (t->parent->parent->right)
u_isBlack = t->parent->parent->right->isBlack;
}
if (!t->isBlack && !u_isBlack)
{
cout << " recolor ";
recolor(t);
}
else if (!t->isBlack && u_isBlack)
{
if (t->isLeft && t->parent->isLeft)
{
cout << " right-rotation ";
right_rotate(t);
}
else if (!t->left && !t->parent->isLeft)
{
cout << " left-rotation ";
left_rotate(t);
}
else if (t->isLeft && !t->parent->isLeft)
{
//right_left_rotate(t);
}
else if (!t->isLeft && t->parent->isLeft)
{
// left_right_rotate(t);
}
else
;
}
}
t = t->parent;
}
cout << "\n\n";
root->isBlack = true;
}
void RBtree::recolor(Node *t)
{
Node *u; // uncle;
if (!t->isLeft)
u = t->parent->parent->left;
else
u = t->parent->parent->right;
t->parent->isBlack = true;
t->parent->parent->isBlack = false;
u->isBlack = true;
}
void RBtree::left_rotate(Node *t)
{
Node *p = t->parent;
Node *g = p->parent;
if (!g->parent) // if grand parent has no parent then it is root
{
// disconnect nodes
g->right = nullptr;
p->parent = nullptr;
// parents left child
Node *p_left = p->left;
if (p_left)
{ // if left child of parent exists disconnect it
p->left = nullptr;
p_left->parent = nullptr;
}
root = p;
root->left = g;
g->parent = p;
g->isLeft = true;
if (p_left)
{
g->right = p_left;
p_left->parent = g;
p_left->isLeft = false;
}
}
else
{
Node *pg = g->parent; // grand parent's parent
pg->right = nullptr;
g->right = nullptr;
g->parent = nullptr;
p->parent = nullptr;
Node *p_left = p->left;
if (p_left)
{
p->left = nullptr;
p_left->parent = nullptr;
}
pg->right = p;
p->parent = pg;
p->left = g;
g->parent = p;
g->isLeft = true;
if (p_left)
{
g->right = p_left;
p_left->parent = g;
p_left->isLeft = false;
}
}
// recolor
p->isBlack = true;
t->isBlack = false;
g->isBlack = false;
}
void RBtree::right_rotate(Node *t)
{
Node * p = t->parent; // parent
Node * g = p->parent; // grand-parent
Node * u = g->right; // uncle
if (!g->parent) // if grand-parent's parent is null then g is root
{
g->left = nullptr;
p->parent = nullptr;
Node *p_right = p->right;
if (p_right)
p_right->parent = nullptr;
root = p;
root->right = g;
g->parent = p;
g->isLeft = false;
if (p_right)
{
g->left = p_right;
p_right->parent = g;
p_right->isLeft = true;
}
}
else
{
Node *pg = g->parent;
pg->left = nullptr;
g->parent = nullptr;
g->left = nullptr;
Node *p_right = p->right;
if (p_right)
p_right->parent = nullptr;
pg->left = p;
p->parent = pg;
p->right = g;
g->parent = p;
g->isLeft = false;
if (p_right)
{
g->left = p_right;
p_right->parent = g;
p_right->isLeft = true;
}
}
// recolor
p->isBlack = true;
t->isBlack = false;
g->isBlack = false;
}
int main()
{
RBtree a;
a.insert(1);
a.insert(2);
a.insert(3);
a.insert(4);
a.insert(5);
a.insert(6);
a.insert(7);
a.insert(8);
a.print_inorder();
}

Linked list insertion not working correctly C++

I am currently trying to insert into a linked list and I'm not sure what I'm doing wrong I know I'm almost there just can't seem to pin down this bug. The printing is happening in printList but I think the logic there is pretty solid.
`
#include <iostream>
#include <fstream>
using namespace std;
struct listBinTreeNode{
public:
string chStr;
int prob = 0;
listBinTreeNode *next;
listBinTreeNode *left;
listBinTreeNode *right;
listBinTreeNode()
{
chStr = "dummy";
next = nullptr;
left = nullptr;
right = nullptr;
}
listBinTreeNode(string chStr, int prob)
{
this->chStr = chStr;
this->prob = prob;
next = nullptr;
left = nullptr;
right= nullptr;
}
listBinTreeNode(string chStr, listBinTreeNode *next, listBinTreeNode* left, listBinTreeNode* right)
{
this->chStr = chStr;
this->next = next;
this->left = left;
this->right = right;
}
void printNode(string fileOut)
{
ofstream outFile;
outFile.open(fileOut);
cout<< "chStr: " <<chStr<< "next's chStr: " << next->chStr << "left's chStr: "<< left->chStr<< "right's chStr: " << right->chStr<< endl;
outFile<< "chStr: " <<chStr<< "next's chStr: " << next->chStr << "left's chStr: "<< left->chStr<< "right's chStr: " << right->chStr<< "\n";
outFile.close();
}
};
class HuffmanLinkedList{
public:
listBinTreeNode * listHead=nullptr;
listBinTreeNode * oldListHead=nullptr;
listBinTreeNode dummy;
HuffmanLinkedList()
{ //listBinTreeNode *dummy = new listBinTreeNode();
listHead = &dummy;
}
void constructHuffmanLList(string fileIn, string fileOut)
{
ifstream inFile;
inFile.open(fileIn);
//fstream outFile.open(fileOut);
// listBinTreeNode *dummy = new listBinTreeNode();
listHead = &dummy;
string word;
int wordProb;
listBinTreeNode spot;
while(inFile >> word >> wordProb)
{
spot = findSpot(listHead,wordProb);
// cout<< "this is spot: "<< spot<<endl;
// cout << "this is listHead.next: "<< listHead->next;
listBinTreeNode *newNode = new listBinTreeNode(word, wordProb);
listInsert(spot, *newNode);
printList(fileOut, listHead);
} // while
inFile.close();
// outFile.close();
}
listBinTreeNode findSpot(listBinTreeNode* head, int prob)
{
listBinTreeNode * walker = head;
while( (walker->next !=nullptr) && (prob > (walker->next->prob) )){
cout<< "here";
walker = walker->next;
}
//if(walker == head){
// return walker->next;
// }
return *walker;
}
void listInsert(listBinTreeNode spot, listBinTreeNode newNode)
{
//if(spot.next!=nullptr){
newNode.next = spot.next;
spot.next = &newNode;
//}
//spot.next = newNode;
cout<< spot.next->chStr<< endl;
}
void printList(string file, listBinTreeNode* head)
{
ofstream outFile;
outFile.open(file);
listBinTreeNode* walker = head;
while(walker->next!=nullptr){
if(walker == head){
cout<<"listHead -->";
outFile<<"listHead -->";
}
if(walker->next!=nullptr){
cout << "("<< walker->chStr << ","<<walker->prob << ","<< walker->next->chStr<<") -->";
outFile << "("<< walker->chStr << ","<<walker->prob << ","<< walker->next->chStr<<") -->";
walker = walker->next;
}
}
cout << "(" << walker->chStr<<", NULL)"<<endl;
outFile <<"(" << walker->chStr<<", NULL)--> NULL"<<"\n";
}
// outFile.close();
};
main:
int main(int argc, char **argv)
{
HuffmanLinkedList linkedList;
HuffmanBinaryTree binTree;
linkedList.constructHuffmanLList(argv[1], argv[4]);
// binTree.constructHuffmanBinTree(linkedList, argv[6]);
// string code = binTree.holder.code;
// binTree.constructCharCode(binTree.root,code, argv[2]);
// binTree.preOrderTraversal(binTree.root,argv[3]);
// binTree.inOrderTraversal(binTree.root,argv[4]);
// binTree.postOrderTraversal(binTree.root,argv[5]);
return 0;
}
argv[1]:
d 2
f 4
h 15
k 6
m 47
p 25
w 1
my output is :
d
(dummy, NULL)
f
(dummy, NULL)
h
(dummy, NULL)
k
(dummy, NULL)
m
(dummy, NULL)
p
(dummy, NULL)
w
(dummy, NULL)
Process returned 0 (0x0) execution time : 0.032 s
Press any key to continue.

BFS for graphs using link list, c++

I tried to implement BFS for graphs using link list but i have some issues with it, using a queue it only displays the nodes of that origin and not after it. The answer should be 2031 but i only get 203.
The code is below:
#include <iostream>
#include <cmath>
#include <vector>
#include <stdlib.h>
#include <queue>
using namespace std;
class linkListNode
{
public:
linkListNode *next;
int destination;
bool visited;
linkListNode()
{
next = NULL;
destination =0;
visited=false;
}
};
class linkList
{
public:
linkListNode *head;
linkList()
{
head = NULL;
}
// append type insert
void insert(int value)
{
linkListNode *temp2 = new linkListNode;
temp2->destination = value;
temp2->next = NULL;
linkListNode *nodePtr = new linkListNode;
if (head == NULL)
{
head = temp2;
temp2->next = NULL;
}
else
{
nodePtr = head;
while (nodePtr->next)
{
nodePtr = nodePtr->next;
}
nodePtr->next = temp2;
}
}
void display()
{
linkListNode *temp = new linkListNode;
temp = head;
while (temp)
{
cout << temp->destination << " --> ";
temp = temp->next;
}
cout << endl;
}
int size()
{
linkListNode *temp = head;
int sizer = 0;
while (temp)
{
sizer++;
temp = temp->next;
}
return sizer;
}
};
class edge
{
public:
int origin;
linkList final;
bool visited;
edge()
{
//origin = NULL;
//cost=0;
visited=false;
}
};
class graph
{
private:
vector <edge> vectorOfEdges;
int vertices;
public:
graph(int v)
{
vertices = v;
vectorOfEdges.clear();
}
void addRoute(int ori, int dest)
{
int counter = 0;
for (int i = 0; i<vectorOfEdges.size(); i++)
{
edge e = vectorOfEdges[i];
if (e.origin== ori)
{
counter = 1; // means element was present in the list
e.final.insert(dest);
}
vectorOfEdges[i] = e;
}
if (counter == 0) // when counter is set to zero, this means that the element was not found in the vector and needs to be pushed
{
edge e;
e.origin = ori;
e.final.insert(dest);
vectorOfEdges.push_back(e);
}
}
void printGraph()
{
edge e;
for (int i = 0; i<vectorOfEdges.size(); i++)
{
e = vectorOfEdges[i];
cout << e.origin << ":- ";
e.final.display();
cout << endl;
}
}
int sizeOfEdge(edge e)
{
int x = e.final.size() + 1;
return x;
}
int max(int one, int two)
{
if (one > two)
{
return one;
}
else
{
return two;
}
}
void BFS(int start)
{
edge e;
queue <int> q;
int save_index=0;
for (int i=0;i<vectorOfEdges.size();i++)
{
e=vectorOfEdges[i];
if (e.origin == start)
{
save_index=i;
q.push(e.origin);
e.visited=true;
break;
}
}
while (!q.empty())
{
int x=q.front();
cout << x << " " ;
q.pop();
linkListNode *l = e.final.head;
while (l)
{
if (l->visited == false)
{
q.push(l->destination);
l->visited=true;
l=l->next;
}
else
{
l=l->next;
}
}
}
}
};
int main()
{
graph g(4);
g.addRoute(0, 1);
g.addRoute(0, 2);
g.addRoute(1, 2);
g.addRoute(2, 0);
g.addRoute(2, 3);
// g.printGraph();
//cout << "Following is Breadth First Traversal (starting from vertex 2) \n";
g.BFS(1);
}
Your code is only running for the node that you have provided as the starting value for your BFS traversal.
void BFS(int start)
{
queue<int> q;
bool startFound = false;
for (int i = 0; i < vectorOfEdges.size(); i++)
{
edge e = vectorOfEdges[i];
if (e.origin == start)
{
q.push(e.origin);
check.push_back(e.origin);
e.visited = true;
startFound = true;
break;
}
}
if (!startFound)
{
cout << "Start vertex not found in the graph" << endl;
return;
}
while (!q.empty())
{
int x = q.front();
cout << x << " ";
q.pop();
for (int i = 0; i < vectorOfEdges.size(); i++)
{
edge e = vectorOfEdges[i];
if (e.origin == x)
{
linkListNode *l = e.final.head;
while (l != NULL)
{
bool found = false;
if (l->visited == false)
{
l->visited = true;
for (int i = 0; i < check.size(); i++)
{
if (check[i] == l->destination)
{
found = true;
break;
}
}
if (found == false)
{
check.push_back(l->destination);
q.push(l->destination);
}
}
l = l->next;
}
}
}
}
}
Instead, do this to run it for every node.

C++ AVL Tree balancing Issues

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.

user defined hash table with value as function pointer

Below is my code
to create hashtable with key as Char* and value as Function pointer
// hash1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <iomanip>
#define SIZE_KEY 16
#define SIZE_VALUE1 64
#define SIZE_VALUE2 16
#define DEFAULT_TABLESIZE 101
using namespace std;
typedef void (*FunctionPtr)();
typedef void (*FunctionPtr1)();
void (*FunctionPtr2)();
void ping(){
cout<<"hello";
}
void refresh(){
cout<<"refresh";
}
typedef struct NODE
{
NODE(char* Key1,FunctionPtr func_ptr)
{
strcpy_s(Key,Key1);
FunctionPtr1 func_ptr1;
func_ptr1=func_ptr;
next = NULL;
}
NODE(){
}
char Key[SIZE_KEY];
FunctionPtr1 func_ptr1[SIZE_VALUE1];
NODE *next;
};
class Hashtable
{
private:
int table_size;
NODE** table;
int size;
long hashString(char* Key);
NODE* find(char* Key);
NODE* current_entry;
public:
int current_index;
Hashtable(int T = DEFAULT_TABLESIZE);//constructor
virtual ~Hashtable();//destructor
bool put(NODE *);
bool get(NODE *);
bool contains(char* Key);
void removeAll();
int getSize();
void initIterator();
bool hasNext();
void getNextKey(char* Key);
friend void disp(NODE *);
};
Hashtable::Hashtable(int T)
{
size = 0;
table_size = T;
table = new NODE*[table_size];
for(int i=0; i<table_size; i++)
{
table[i] = NULL;
}
}
Hashtable::~Hashtable()
{
removeAll();
delete[] table;
}
bool Hashtable::put(NODE *N)
{//start put
if(find(N->Key) != NULL)
{
return false;
}
//NODE* entry = new NODE( N->Key ,*(FunctionPtr *)N->func_ptr1 );
NODE* entry = new NODE( N->Key ,*(FunctionPtr *)N->func_ptr1 );
int bucket = hashString(N->Key);
entry->next = table[bucket];
table[bucket] = entry;
size++;
return true;
}//end put
bool Hashtable::get(NODE* N)
{//start get
NODE* temp = find(N->Key);
if(temp == NULL)
{
*(FunctionPtr *)N->func_ptr1 = refresh;
return false;
}
else
{
*(FunctionPtr *)N->func_ptr1= *(FunctionPtr *)temp->func_ptr1;
return true;
}
}//end get
bool Hashtable::contains(char* Key)
{//start contains
if(find(Key) == NULL)
{
return false;
}
else
{
return true;
}
}//end contains
void Hashtable::removeAll()
{//start removeAll
for(int i=0; i<table_size; i++)
{
NODE* temp = table[i];
while(temp != NULL)
{
NODE* next = temp->next;
disp(temp);
delete temp;
temp = next;
}
}
size = 0;
}//end removeAll
int Hashtable::getSize()
{
return size;
}
NODE* Hashtable::find(char* Key)
{ //start find
int bucket = hashString(Key);
NODE* temp = table[bucket];
while(temp != NULL)
{
if(strcmp(Key, temp->Key) == 0)
{
return temp;
}
temp = temp->next;
}
return NULL;
}//end find
long Hashtable::hashString(char* Key)
{//start hashString
int n = strlen(Key);
long h = 0;
for(int i=0; i<n; i++)
{
//To get almost fair distributions of NODEs over the array
h = (h << 3) ^ Key[i];
}
return abs(h % table_size );
}//end hashString
void Hashtable::initIterator()
{//start initIterator
current_entry = NULL;
current_index = table_size;
for(int i=0; i<table_size; i++)
{
if(table[i] == NULL)
{
continue;
}
else
{
current_entry = table[i];
current_index = i;
break;
}
}
}//end initIterator
bool Hashtable::hasNext()
{
if(current_entry == NULL)
{
return false;
}
else
{
return true;
}
}
void Hashtable::getNextKey(char* Key)
{
if(current_entry == NULL)
{
Key[0] = '\0';
return;
}
strcpy(Key, current_entry->Key);
if(current_entry->next != NULL)
{
current_entry = current_entry->next;
}
else
{
for(int i=current_index+1; i<table_size; i++)
{
if(table[i] == NULL)
{
continue;
}
current_entry = table[i];
current_index = i;
return;
}
current_entry = NULL;
current_index = table_size;
}
}
void dispAll(Hashtable* hashtable);
int main()
{
char temp1[SIZE_KEY];
Hashtable* hashtable = new Hashtable();
NODE N1("1",ping);
if(!hashtable->contains(N1.Key))
{
cout << "\nAdding NODE: ";
disp(&N1);
hashtable->put(&N1);
}
// dispAll(hashtable);
strcpy(N1.Key, "314");
*(FunctionPtr *) N1.func_ptr1=refresh;
if(!hashtable->contains(N1.Key))
{
cout << "\nAdding NODE: ";
disp(&N1);
hashtable->put(&N1);
}
/* strcpy(N1.Key, "320");
*(FunctionPtr *) N1.func_ptr1= ping;
if(!hashtable->contains(N1.Key))
{
cout << "\nAdding NODE: ";
disp(&N1);
hashtable->put(&N1);
}
strcpy(N1.Key, "768");
*(FunctionPtr *)N1.func_ptr1= refresh;
if(!hashtable->contains(N1.Key))
{
cout << "\nAdding node: ";
disp(&N1);
hashtable->put(&N1);
}
strcpy(N1.Key, "756");
*(FunctionPtr *) N1.func_ptr1= refresh;
if(!hashtable->contains(N1.Key))
{
cout << "\nAdding node: ";
disp(&N1);
hashtable->put(&N1);
} */
dispAll(hashtable);
// strcpy(temp1,"314");
// hashtable->remove(temp1);
// cout << "\n\nAfter removing 314:" << endl;
// dispAll(hashtable);
cout << "\n\nDestroying hashtable:" << endl;
delete hashtable;
return 0;
}
void disp(NODE *N1)
{
cout << "\nKey: " << N1->Key << "\nFunction "
<< N1->func_ptr1 << endl;
// FunctionPtr2();
}
void dispAll(Hashtable *hashtable)
{
NODE N1;
cout << "\n\nCurrent nodes in hashtable:" << endl;
hashtable->initIterator();
while(hashtable->hasNext())
{
//cout<<"Current Index === "<<hashtable->current_index;
hashtable->getNextKey(N1.Key);
hashtable->get(&N1);
disp(&N1);
}
}
each time data is written in hash table VALUE cointains the same address :(
i want address of particular function that i will send..
Some of the problems may be in struct NODE.
typedef struct NODE
{
NODE(char* Key1,FunctionPtr func_ptr)
{
strcpy_s(Key,Key1);
FunctionPtr1 func_ptr1; // <-- Problem may be here
func_ptr1=func_ptr;
next = NULL;
}
NODE(){
}
char Key[SIZE_KEY];
FunctionPtr1 func_ptr1[SIZE_VALUE1]; // <-- And here
NODE *next;
};
You declared a local func_ptr1 in NODE::NODE(char*, FunctionPtr), and assign the parameter func_ptr to func_ptr1. Thus, func_ptr is assigned to a local variable, not a member variable. And, once the constructor returns, nothing about the function pointer is remembered.
Another problem: why is NODE::func_ptr1 an array of FunctionPtr1? I don't think you intended to store multiple function pointers in one NODE instance.