I am implementing a tree which is a Binary Expression Tree. The leaf nodes are numbers, non-leaf nodes are math operators. Succesfully implemented printInorder,PostOrder, PreOrder, evaluate. But stucked with the printLevel().
Here is my int main ()
int main()
{
EXTree myTree;
string tests[] = {"2.1*3.1+4.2", "(2.0+1.3)/1.4", "2.*(1.3+1.4)","1.2*(1.3+1.4/0.5)","1.2*(1.3+1.4/0.5)-4.4", "1.2*(1.3+1.4/0.5)- (9/3)"};
for (int i=0; i < 6; i++)
{
myTree.build (tests[i]);
myTree.printInorder();
myTree.printPreorder();
myTree.printPostorder();
myTree.printLevel(); //Starting from level = 0
cout << "Evaulating myTree = " << format(myTree.evaluate(),2) << endl;
myTree.removeAll(); // removes all the nodes
}
}
printLevel(); only prints the level of the tree given above and its initally 0.
and here is my printLevel function.
void EXTree:: printLevel()
{
queue<Node*> levelq;
levelq.push(root);
cout << "Current Level is: ";
while( levelq.size() > 0 )
{
Node *cur = levelq.front();
cout << cur->Root << " ";
levelq.pop();
if (cur->Left) levelq.push(cur->Left);
if (cur->Right) levelq.push(cur->Right);
}
cout << endl;
}
But I really didnt understand how to implement the printLevel. Appreciate for any help to clarify it.
I just implemented the inOrder algorith to my printLevel and tried to change it but still didnt get it.
Since you have no problem with recursion, this would work without queue:
void EXTree:: printLevel()
{
int currentLevel = 0;
if (root)
{
cout << "Current Level is: ";
printLevelHelper(root,currentLevel);
}
else
cout << "This BST is Empty\n";
}
// Declare a private method:
void EXTree:: printLevelHelper(Node* &n, int ¤tLevel)
{
cout << currentLevel << ' ';
if (n->Left)
{
currentLevel++;
printLevelHelper(n->Left,currentLevel);
currentLevel--;
}
if (n->Right)
{
currentLevel++;
printLevelHelper(n->Right,currentLevel);
currentLevel--;
}
}
When using Breadth First Search to print the nodes on one level immediately adjacent to each other, you'd just observe when the leftmost child of the leftmost node on the current level pops out of the queue: this must be the start of the next level. I could easily write the code but I'd guess it would incomprehensible for you and this homework is for you (I think you want to label your post appropriately as homework, BTW). Most of your implementation looks like a straight forward implementation. The only thing missing is detecting that the next level is reached.
Related
So I'm a little new to Binary search trees and I'm trying to make a binary tree where each node is a vector of strings. then each insertion takes a string and only considers the first letters of that string. Based off the first 2 letters it will either append that string to an existing node where all string share the same 2 first letters or create a new node which will hold a vector of strings with all the same 2 first letters. Weird I know. It wasn't my idea.
I've tried narrowing down where the issue is by displaying the root at every insertion. And the insertions all seem to be working fine, but as soon as I want to display the nodes in Inorder, the root just seems to disappear, BUT almost like it's invisible. It's very evident base on the output. My guess is that it's null but I'm not sure. Sorry if this isn't the best way to ask. this is my first question here.
here's my code:
#include <iostream>
#include <string>
#include <vector>
//#include "stringSlicer.h"
using namespace std;
class BST
{
vector<string> data;
BST *left, *right;
public:
// Default constructor.
BST();
// Parameterized constructor.
BST(string);
// Insert function.
BST* Insert(BST*, string);
// Inorder traversal.
void Inorder(BST*);
// PreOrder Traversal.
void PreOrder(BST*);
// PostOrder Traversal
void PostOrder(BST*);
// string slicer
string strSlice(string);
// print vector
void printVector(vector<string>);
};
// Default Constructor definition.
BST ::BST()
: data(0)
, left(NULL)
, right(NULL)
{
}
// Parameterized Constructor definition.
BST ::BST(string value)
{
if(data.empty()){
data.push_back(strSlice(value));
}
data.push_back(value);
left = right = NULL;
}
// String slicing function definition
string BST ::strSlice(string word){
string word2 = "";
word2 += word[0];
word2 += word[1];
return word2;
}
// print vector function definition
void BST ::printVector(vector<string> dataVector){
for(int i = 0; i < dataVector.size(); i ++){
cout << dataVector.at(i) << " ";
cout << "end of this node";
}
}
// Insert function definition.
BST* BST ::Insert(BST* root, string value)
{
if (!root)
{
// Insert the first node, if root is NULL.
return new BST(value);
}
// Insert data.
if (strSlice(value).compare(root->data.at(0)) > 0)
{
// Insert right node data, if the 'value'
// to be inserted is greater than 'root' node data.
cout << value << " is being put in the right node " << value << " > " << root->data.at(0) << endl;
// Process right nodes.
root->right = Insert(root->right, value);
} else if (strSlice(value).compare(root->data.at(0)) == 0) {
cout << value << " is being put in the same node " << value << " = " << root->data.at(0) << endl;
root->data.push_back(value);
}
else
{
// Insert left node data, if the 'value'
// to be inserted is greater than 'root' node data.
cout << value << " is being put in the left node " << value << " < " << root->data.at(0) << endl;
// Process left nodes.
root->left = Insert(root->left, value);
}
// Return 'root' node, after insertion.
cout << "after insert root is " << root << endl;
return root;
}
// Inorder traversal function.
// This gives data in sorted order.
void BST ::Inorder(BST* root)
{
cout << "root is " << endl;
if (!root) {
return;
}
Inorder(root->left);
printVector(data);
cout << endl;
Inorder(root->right);
}
int main() {
const int size = 5;
string array [size] = {"hi","hillo","bye","chao","elo"};
BST b, *root = NULL;
cout << "root is " << root << endl;
root = b.Insert(root, array[0]);
for (int i = 1; i < size; i ++){
b.Insert(root, array[i]);
}
b.Inorder(root);
return 0;
}
here was the output:
root is 0
hillo is being put in the same node hillo = hi
after insert root is 0xeb7f10
bye is being put in the left node bye < hi
after insert root is 0xeb7f10
chao is being put in the left node chao < hi
chao is being put in the right node chao > by
after insert root is 0xeb7f30
after insert root is 0xeb7f10
elo is being put in the left node elo < hi
elo is being put in the right node elo > by
elo is being put in the right node elo > ch
after insert root is 0xeb7f88
after insert root is 0xeb7f30
after insert root is 0xeb7f10
root is
root is
root is
root is
root is
root is
root is
root is
root is
Problem:
Your nodes are not NULL, but you're not printing the data of any of them. With the statement printVector(data); you're printing just the data of the object b.
Solution:
Change printVector(data); to printVector(root->data);.
Additional information:
using namespace std; is considered a bad practice (More info here).
Instead of creating an object b just to use the methods of the class BST, make the methods static and pass the node as an argument. It's cleaner and will help to avoid confusions as this case.
Personally I would recommend you to use nullptr instead of NULL in C++.
Even if root is NULL, the Inorder method will execute "cout << "root is " << endl;" before returning and therefore outputting unnecesary lines.
You should use delete to free the data you store with new.
Question: I keep receiving exc_bad_access (process code 11) error. Is this due to a bad algorithm or simply a coding error? Can anyone help me fix it?
My class assignment is to create a binary search tree whose nodes can store a name, a balance, and a key. Nodes are to be organized and searched for using the key. This tree should support insertion, inorder traversal, and searching based on a key (I haven't built this function yet). I've also included several other functions to facilitate building these. If it matters, I'm using CLion on OSX High Sierra. Additionally, I get the error on the first prompt to enter node information, the error does not seem to be related to the input itself.
//Genghis Khan
#include <iostream>
#include <vector>
using namespace std;
class node
{
public:
int key;
string name;
double balance;
node *leftptr;
node *rightptr;
friend class tree;
};
class tree
{
public:
node *root, *temp, *v;
//Constructor
tree()
{
root = NULL;
temp = root;
}
bool empty()
{
return(root == NULL);
}
bool isleaf(node *x)
{
return((x->leftptr == NULL) && (x->rightptr == NULL));
}
void inorder(node *temp)
{
if(~isleaf(temp))
{
inorder(temp->leftptr);
cout << "Name: " << temp->name << " " << "Balance: " <<
temp->balance << " " << "Key: " << temp->key;
inorder(temp->rightptr);
}
}
node* createnode()
{
v = new node;
cout << "Enter name (string): " << endl;
getline(cin, v->name);
cout << "Enter key (integer): " << endl;
cin >> v->key;
cout << "Enter balance (double): " << endl;
cin >> v->balance;
return(v);
}
void set()
{
temp = root;
}
void insert(node *v)
{
while(~isleaf(temp))
{
if((v->key < temp->key))
{
temp = temp->leftptr;
insert(v);
}
else if(v->key > temp->key)
{
temp = temp->rightptr;
insert(v);
}
}
temp->key = v->key;
temp->balance = v->balance;
temp->name = v->name;
}
};
int main()
{
int n;
cout << "Enter number of people: ";
cin >> n;
//Creating instance of tree, inserting all data into tree
tree b;
for(int i = 0; i < n; i++)
{
b.set();
node *a = b.createnode();
b.insert(a);
}
//inorder part
b.set();
b.inorder(b.temp);
}
The functions are (pseudocode):
1. function isleaf(x): return(x's left pointer and x's right pointer are both NULL)
2. function set(): set temp to root //temp will be reset every time an insertion, traversal, or search occurs
3. function createnode():
v is a new node
get all the fields for v
return v
4. function insert(v)
while(not isleaf(temp)):
-if(v's key < temp's key)
temp = temp's left pointer (to the lower value child node)
insert(node *v)
-if(v's key > temp's key)
temp = temp's right pointer (to the higher value child node)
insert(node *v)
end while
duplicate v's data to temp, now that temp is a leaf
5. function inorder(temp):
if(not isleaf(temp):
inorder(temp's left pointer)
output all info in temp node
inorder(temp's right pointer)
Main Algorithm
for the number of nodes to be entered:
1. set
2. node *a = createnode
3. insert(a)
Update
The error seems to be coming from the 'if((v->key < temp->key))' line.
EXC_BAD_ACCESS just means that you are trying to access an invalid memory. By a quick brief, your function isleaf doesn't check whether x is null.
May have other errors, you can debug and find it by yourself.
Here is some code that I have made that should copy all the nodes in a linked data type correctly, but it is not working. I have checked my logic and wrote it on paper many times, yet it still isn't working. Am I doing something wrong on this part of the code? Is my use of pointers to copy nodes accurate? The part of my Constructor test that goes haywire is the part that starts to print out what's in the queue.
void LinkedQueue<ItemType>::CopyNodesFrom(const LinkedQueue& a_queue)
{
Node<ItemType>* orig_chain_ptr = a_queue.front_ptr_; // Points to nodes in original chain
if (orig_chain_ptr == nullptr) {
front_ptr_ = nullptr; // Original queue is empty
back_ptr_ = nullptr;
return;
}
// Copy first node
front_ptr_ = new Node<ItemType>();
front_ptr_->SetItem(orig_chain_ptr->GetItem());
// Advance original-chain pointer
orig_chain_ptr = orig_chain_ptr->GetNext();
// Copy remaining nodes
Node<ItemType>* new_chain_ptr = front_ptr_; // Points to last node in new chain
Node<ItemType>* temp_ptr;
while (orig_chain_ptr != nullptr) {
temp_ptr = new Node<ItemType>(orig_chain_ptr->GetItem() );
new_chain_ptr->SetNext(temp_ptr);
orig_chain_ptr = orig_chain_ptr->GetNext(); //Advance Our original pointer
new_chain_ptr = new_chain_ptr->GetNext(); //Advance our new chain pointer
} // end while
new_chain_ptr->SetNext(nullptr);
back_ptr_ = new_chain_ptr;
} // end copy constructor
#include <iostream>
#include <string>
#include "LinkedQueue.h" // ADT Queue operations
using namespace std;
void CopyConstructorAndAssignmentTester() {
LinkedQueue<string> queue;
string items[] = {"zero", "one", "two", "three", "four", "five"};
for (int i = 0; i < 6; i++) {
cout << "Adding " << items[i] << endl;
bool success = queue.Enqueue(items[i]);
if (!success)
cout << "Failed to add " << items[i] << " to the queue." << endl;
}
cout << "Queue contains, from front to back, zero one two three four five." << endl;
cout << "Checking Copy Constructor tester " << endl;
LinkedQueue<string> copy_of_queue(queue);
cout << "Copy of queue contains, from front to back, ";
for (int i = 0; i < 6; i++)
{
cout << " " << copy_of_queue.PeekFront();
copy_of_queue.Dequeue();
}
cout << "." << endl;
/*
cout << "Checking Assignment Operator tester " << endl;
LinkedQueue<string> assigned_queue;
assigned_queue.Enqueue("ha");
assigned_queue.Enqueue("ba");
assigned_queue = queue;
cout << assigned_queue << endl;*/
/* cout << "Assigned queue contains, from front to back, ";
for (int i = 0; i < 6; i++)
{
cout << " " << assigned_queue.PeekFront();
assigned_queue.Dequeue();
}
cout << "." << endl;
cout << "Original queue contains, from front to back,";
for (int i = 0; i < 6; i++) {
cout << " " << queue.PeekFront();
queue.Dequeue();
}
cout << "." << endl << endl; */
} // end copyConstructorTester
int main()
{
CopyConstructorAndAssignmentTester();
char a;
cin >> a;
//ConcatenateTester();
//return 0;
} // end main
EDIT: Oh crap, this stumps more people than I thought. XD. I thought I made a blatantly obvious mistake.
This may not be the answer you are looking for, and I'm finding it difficult to spot mistakes in your code lacking the full information of the states being manipulated.
The linked list logic looks all right: nothing jumps out at me as being faulty there in terms of the logic used to copy. Put in a distilled form:
first_node = last_node = new Node(other.first_node->data);
for (Node* other_node = other.first_node->next; other_node; other_node = other_node->next)
{
Node* new_node = new Node(other_node->data);
last_node->next = new_node;
last_node = new_node;
}
last_node->next = nullptr;
I believe this is what you have and it should be correct in terms of the overall logic. Any problems will probably be found elsewhere. Nevertheless, it should make your life easier to reduce the number of states you're working with. This 'new_chain_ptr' is unnecessary and you can just write out the results to 'back_ptr_' directly.
However, I have a different suggestion. You have the rest of the Queue working correctly, yes, including these methods like 'Enqueue'? If so, your copy constructor can be more trivially implemented just using what works already. Start with the state for an empty queue, and then read the elements from the other queue and 'Enqueue' those elements into your copy. Now you can avoid getting yourself tangled up in the low-level linked list logic by utilizing the parts you already know are functioning like so:
// Create empty queue.
first_node = last_node = nullptr;
// Enqueue elements from other queue.
for (Node* other_node = other.first_node; other_node; other_node = other_node->next)
Enqueue(other_node->data);
It might cost you an additional branch or so per iteration but remember that correctness always precedes efficiency, and you can come back and optimize once you have it working. Remember to handle self-assignment if the logic cannot work properly in those cases.
And yes, a debugger will give you a massive edge in accelerating the understanding of the nature of your code in addition to spotting mistakes more quickly.
I am trying to debug a bfs algorithm using a adjacent list. It will print correctly to a certain point then goes into infinite loop. I did some printouts and noticed that it eventually loops over the first two nodes of the graph. I am not sure where in my code thats causing this problem. This is anassignment I was given, and this is my last resort. If anyone can point me in the right direction as to what the problem could be would help alot.
void bfsList(linkedList adjList[], int visit[], int j){
Queue queue(24);
if (visit[j] == 0){
cout << j+1 << endl;
visit[j] = 1;
queue.enqueue(j);
while(!queue.isEmpty()){
int k = queue.dequeue();
//queue.print();
for(int i=0;i<adjList[k].len();i++){
if (visit[adjList[k].elementAt(i)-1]==0){
cout << adjList[k].elementAt(i) << endl;
visit[adjList[k].elementAt(i)-1] = 1;
}
if (!queue.isFull()){
queue.enqueue(adjList[k].elementAt(i)-1);
}
}
}
}
}
Enqueue only if node is not visited.
if (visit[adjList[k].elementAt(i)-1]==0){
cout << adjList[k].elementAt(i) << endl;
visit[adjList[k].elementAt(i)-1] = 1;
if (!queue.isFull()){
queue.enqueue(adjList[k].elementAt(i)-1);
}
}
queue.enqueue(adjList[k].elementAt(i)-1);
needs to be dependent, whether the node has been visited.
untested:
if (!queue.isFull() && !visit[adjList[k].elementAt(i)-1]){
queue.enqueue(adjList[k].elementAt(i)-1);
}
so I have been trying to get an old c++ binary search tree program of mine to work.It compiles and runs but I do not get the results I would expect. If I insert c,d,a,b in that order and try to remove c, my remove function skips the if conditionals that find in order successors. Why are those 2 else if conditionals skipped?
Also it is compiled using gcc.
Node::Node(string nodeItem,
int nodeLine){
item=nodeItem;
vector<int> tempVector;
tempVector.push_back(nodeLine);
lines=tempVector;
leftPtr = NULL;
rightPtr = NULL;
}
// recursive method for finding node containing the word
Node* BST::find(string data, Node *curr) {
if(curr==NULL) {
cout << data << " is not in the tree" << endl;
return curr;
}
if(curr->getItem().compare("theplaceholder")==0){
return curr;
}
string tempItem = curr->getItem();
//this if statement is if I am inserting a word that is already in the tree
// or if I am removing the word from the tree
if(data.compare(tempItem)==0){
return curr;
}
else if(data.compare(tempItem)<0){
return find(data,curr->getLeftPtr());
}
else{
return find(data, curr->getRightPtr());
}
}
void BST::insert(string data, int fromLine) {
Node *curr;
curr=find(data, root);
if(curr!=NULL && curr->getItem().compare("theplaceholder")==0){
curr->setData(data);
curr->addLines(fromLine);
}
if(curr==NULL){
// I want to point to a nonNull node.
// I am making a new node and having curr point to that instead of NULL
//then I set it to
curr=new Node(data, fromLine);
cout <<curr->getItem() << endl;
vector<int> foundLines=curr->getNodeLines();
//cout<< "The word " <<curr->getItem() << " can be found in lines ";
if(foundLines.empty())
cout << "foundLines is empty";
int size=foundLines.size();
for(int count=0; count<size; count++){
//cout << foundLines[count] << ", ";
}
}
if(curr->getItem()==data){
curr->addLines(fromLine);
}
}
// remove method I am trying to check for in order successors to swap with the deleted node.
void BST::remove(string data) {
Node *curr=root;
Node *temp=find(data, curr);
if(temp==NULL){
cout << " nothing to remove" << endl;
}
else if(temp->getRightPtr()!=NULL){
curr=temp->getRightPtr();
cout << curr->getItem() << endl;
while(curr->getLeftPtr()!=NULL){
curr=curr->getLeftPtr();
cout << curr->getItem() << endl;
}
temp->setData(curr->getItem());
temp->setLines(curr->getNodeLines());
delete curr;
curr=NULL;
}
else if(temp->getLeftPtr()!=NULL){
cout <<"if !temp->getLeftPtr" << endl;
curr=temp->getLeftPtr();
cout << curr->getItem() << endl;
while(curr->getRightPtr()!=NULL){
curr=curr->getRightPtr();
cout << curr->getItem() << endl;
}
temp->setData(curr->getItem());
temp->setLines(curr->getNodeLines());
delete curr;
curr=NULL;
}
else{
cout <<"else delete temp" << endl;
delete temp;
temp=NULL;
}
}
The reason this line
else if(temp->getRightPtr()!=NULL){
never succeeds is that you never set the right pointer on any node - getRightPtr can only return null. If you'd examined the state of your tree in the debugger after you'd built it or if you stepped through the insert function you'd probably have seen this. The problems are:
your find function doesn't return null if the node isn't in the tree, whereas your insert function expects it will
your insert function needs to locate the position in the tree where this node should be - either through fixing the find function or on its own, then create a new node AND add a reference to it from the parent node, on either the left or right side as appropriate
your insert function appears the line number to the first-inserted node twice: once when you overwrite the placeholder and once at the end of insert (rather than use a placeholder here I'd probably have initialised root to be null and instead set root = curr when you create the first node)
your remove function needs to do more work when promoting the highest node from the left-hand branch; it needs to
correctly clean up that node from it's previous parent - at the moment you delete the object but leave any dangling pointers alone
promote any children of that node before you move it to take its previous slot
i.e.
D C
/ \ / \
A E remove 'D' A E
\ => 'C' is highest on left \
C but need to move B to C B
/
B