I am trying to write a BST() that would take in strings as nodes without using recursion. here is the add function of my code, can you please review and see if it is easy to understand/follow and point out mistakes. I am new to programming and would appreciate any feedback.
#include <iostream>
#include <string>
#include <stack>
#include <queue>
#include <fstream>
#include <cstdlib>
#include <cstring>
using namespace std;
int main() {
class BST {
private:
struct Node {
string value;
Node* left;
Node* right;
};
Node* root;
public:
BST()
{
root = NULL;
}
~BST()
{
stack<Node*> nodes;
nodes.push( root);
while( ! nodes.empty())
{
Node* topNode = nodes.top();
nodes.pop();
if ( topNode->left )
nodes.push(topNode->left);
if ( topNode->right )
nodes.push(topNode->right);
delete topNode;
}
}
Node* GetNewNode(string data){
Node* newNode = new Node();
newNode->value=data;
newNode->left = newNode->right = NULL;
return root;
}
Node* Insert(Node* rootPtr,string data){
if(rootPtr == NULL){
rootPtr = GetNewNode(data);
return rootPtr;
}
else if(data<= rootPtr->value){
rootPtr->left = Insert(rootPtr->left,data);
}
else {
rootPtr->right = Insert(rootPtr->right,data);
}
return rootPtr;
}
};
}
1 - In the insert function:
while (root != NULL) { // this shouldn't be root, the root isn't the node that traverse your tree, this has to be current
.....
}
2- you never add your new node, you just keep looping till you reach a null.
You should traverse your tree till u find the right position to insert your node then add the new node, something like:
current = root;
prev = current;
while (current!= NULL) {
prev = current;
if (current->value.compare(word) < 0)
current = current->left;
else
current = current->right;
}
//here your new node should be on the left or the right of the prev node
3 - in "GetNewNode" return the new node not the root
4 - your delete function is a mess, u shall think about it again and re-implement it.
Finally I strongly recommend you to check and understand a ready made implementation from the web then try to write your BST again.
Related
I am a beginner and am working on Linked list. I am trying to make a program which adds elements to the list, updates the list, dislays it and deletes it.I am getting an exception : read access violation. temp was 0xDDDDDDDD.
I think there is some problem with display() function. The debugger also does shows the same.
#include "stdafx.h"
#include "Node.h"
#include<iostream>
using namespace std;
Node::Node() //constructor
{
head = NULL;
}
Node::~Node() //destructor
{
}
void Node::addFirstNode(int n) //adding the first element in the list
{
node *temp = new node;
temp->data = n;
temp->next = NULL;
head = temp;
}
void Node :: addLast(int n) //Adding elements at the end of the list
{
node *last = new node;
last->data = n;
last->next = NULL;
node *temp = new node;
temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = last;
}
void Node::display() //Displaying the list
{
node *temp = head;
while (temp != NULL)
{
cout<<temp->data;
temp = temp->next;
}
}
//the main function:
#include "stdafx.h"
#include "Node.h"
#include<iostream>
using namespace std;
int main()
{
Node a;
a.addFirstNode(101); //Calling function : addFirstNode
a.addLast(102); //Calling function : addLast
a.addLast(103); //Calling function : addLast
a.addLast(104); //Calling function : addLast
a.display(); //Calling function : display
return 0;
}
The Node.h file is as below:
struct node
{
int data;
node *next;
};
class Node
{
private :
node *head;
public:
Node();
~Node();
void addFirstNode(int n);
void addLast(int n);
void display();
};
You should rename Node to better describe what it is, e.g. List.
In Node::addFirst(), replace temp->next = NULL; with temp->next = head; You don't want to throw away your list every time you add a Node to the beginning of it.
In Node::addLast(), replace node *temp = new node; with node *temp = head; You don't want to leak memory every time you add a Node to the end of it.
Header File:
#ifndef LL_H
#define LL_H
// include this library to use NULL, otherwise use nullptr instead
#include <cstddef>
// include iostream so anything that includes this file can use cout
#include <iostream>
// Struct which will be the building block of our list
struct node
{
int val;
node* next;
};
// Contents of 11.h
// Linked list class definition
class LL
{
public:
LL();
bool removeFront();
bool removeBack();
node* search(int);
void print();
private:
node* head;
};
#endif
Source File:
#include "ll.h"
LL::LL()
{
head = NULL;
}
void LL::search (int num)//heading of the function
{
node* newNode = new node;
newNode->val = num;
newNode->next = NULL;
while (newNode == NULL)
{
if (newNode->val == num)
{
return newNode;
}
newNode = newNode->next; //point to the next node
}
return; //not sure if needed
}
The program will read in a
text file called “cmd.txt” that will instruct what operations to run. our program should implement a C++ class which will be used to represent the linked list.
Search should look more like:
node* LL::Search(int num)
{
node* current = head;
while (current != null)
{
if (current->val == num)
{
return current;
}
current = current->next;
}
return null;
}
This is the correct format
node* LL::search(int num)
{
node* newNode = new node;
newNode = head;
while (newNode->next != NULL)
{
if (newNode->val == num)
{
return newNode;
}
newNode = newNode->next;
}
return NULL;
}
Inserting just one node to the tree works fine, but on inserting the 2nd node onwards, the program crashes. Here is the code:
#include <iostream>
#include <cstring>
using namespace std;
struct node
{
char* key;
node *left, *right;
};
// A utility function to create a new BST node
node *newNode(const char* item)
{
node *temp =new node;
strcpy(temp->key,item);
temp->left = temp->right = NULL;
return temp;
}
// A utility function to do inorder traversal of BST
void inorder(node *root)
{
if (root!= NULL)
{
inorder(root->left);
cout<<root->key<<endl;
inorder(root->right);
}
}
/* A utility function to insert a new node with given key in BST */
node* insert(node* tnode,const char* key)
{
/* If the tree is empty, return a new node */
if (tnode == NULL)
return newNode(key);
/* Otherwise, recur down the tree */
if (strcmp(key,tnode->key) < 0)
tnode->left = insert(tnode->left, key);
else if (strcmp(key,tnode->key) > 0)
tnode->right = insert(tnode->right, key);
/* return the (unchanged) node pointer */
return tnode;
}
// Driver Program to test above functions*/
int main()
{
node *root = NULL;
char* word[]={"elephant","hi","little","nil",NULL};
root = insert(root,word[0]); //works fine
for(int i=1;word[i];i++)
insert(root,word[i]);
// print inoder traversal of the BST
inorder(root);
return 0;
}
after:
root = insert(root,word[0]);
inorder(root);
o/p: elephant
on inserting 2nd node
crashes
You're not initialising the key array that item will get copied into. Try this:
node *newNode(const char* item)
{
node *temp = new node();
temp->key = new char[strlen(item) + 1];
strcpy(temp->key,item);
temp->left = temp->right = NULL;
return temp;
}
That said, there are some more problems with your code, like no destructors etc. I'd strongly recommend reading some good books/tutorials on programming in C++.
I think I am having an issue with the logic in my DeleteNode function in this linked list class. When I test the code it sometimes returns false when the node is in the list, and I haven't found a pattern.
If there is absolutely nothing wrong with this implementation of DeleteNode, the problem could be in the code where I am using the method, but if it is I want to take a look at that on my own before posting that code. (The purpose of me saying that is to let you know this code might be fine, but I want to know for sure).
Thanks so much!
Header file:
#include <string.h>
#ifndef LIST_H
#define LIST_H
class List {
public:
typedef struct node {
char * data;
node * next;
}* nodePtr;
nodePtr curr;
nodePtr temp;
nodePtr head;
public:
List();
void AddNode(char * addData);
bool DeleteNode(char * delData);
bool containsNode(char * Data);
void PrintList();
};
#endif
.cpp file:
#include <iostream>
#include "SLList.h"
using namespace std;
List::List() {
head = NULL;
curr = NULL;
temp = NULL;
}
bool List::DeleteNode(char * delData) {
nodePtr delPtr = NULL;
temp = head;
curr = head;
while (curr != NULL && curr->data != delData) {
temp = curr;
curr = curr->next;
}
if (curr == NULL) {
return false;
}
else {
delPtr = curr;
curr = curr->next;
temp->next = curr;
delete delPtr;
return true;
}
}
So for my assignment, I am supposed to implement a Node class that just contains data and pointers to its two siblings and a BinaryTree that reads in these Nodes and creates a binary tree out of them. My problem is pointing to the root of the Tree does not seem to work. Any help you can provide would be appreciated!
Note: The error is found a few lines into the addNode method in the BinaryTree.cpp file which can be found at the end of the question. Also, I am not able to access the value of size either, so I believe this is some sort of weird scope issues I cannot resolve. I also cannot use the "this" keyword in the addNode function.
I am also not allowed to use structs, per my homeworks' instruction.
Node.H
#include <iomanip>
using namespace std;
class Node
{
public:
int data;
Node* leftChild;
Node* rightChild;
Node(int data, Node* leftChild, Node* rightChild);
};
Node.cpp
#include <iomanip>
#include <iostream>
#include "Node.h"
using namespace std;
Node::Node(int data, Node* leftChild, Node* rightChild)
{
this->data = data;
this->leftChild = leftChild;
this->rightChild = rightChild;
}
BinaryTree.H
#include <iomanip>
#include "Node.h"
using namespace std;
class Tree
{
public:
Tree(int data);
void addNode(int data);
void inOrder(Node* N);
protected:
Node* root;
int size;
int data;
private:
int printNode(Node* N);
};
BinaryTree.cpp
#include <iostream>
#include <iomanip>
#include "BinaryTree.h"
using namespace std;
//Tree constructor. Sets the values of data, size, and root.
Tree::Tree(int data)
{
this->data = data;
this->size = 0;
this->root = new Node(data, NULL, NULL);
}
//Adds a node to the current Tree.
void addNode(int data)
{
Node* tempNode = new Node(data, NULL, NULL);
Node* current = root; //THIS IS THE ERROR LINE.
while(current!=NULL)
{
//If the data we are trying to add is already in the Tree
if(current->data == tempNode->data)
{
cout << "Data already in the Tree.";
}
//If the data for the new node is larger than the old
else if(current->data < tempNode->data)
{
//See if the right child is null. If so, add the tree node there.
if(current->rightChild == NULL)
{
current->rightChild = tempNode;
return;
}
//Otherwise, traverse down the right tree.
else
{
current = current->rightChild;
}
}
//The data is smaller than the current node
else
{
//See if the left child is null. If so, add the tree node there.
if(current->leftChild == NULL)
{
current->leftChild = tempNode;
return;
}
//Otherwise, traverse down the left tree
else
{
current = current->leftChild;
}
}//End of leftChild Else
}//End of while
}//End of addNode
void addNode(int data)
should be:
void Tree::addNode(int data)
as it is a member function of class Tree
//Adds a node to the current Tree.
void addNode(int data)
Should be:
//Adds a node to the this Tree
void Tree::addNode(int data)