I'm learning C++ language and I'm trying to write BST, but something goes wrong.
I try to add element to empty tree, root is NULL, but after adding element root is still NULL despite of the fact that addiing was successful (I saw it in debug mode, node is set as tmp). I have no idea why it happens.
struct Node
{
int data;
Node* left;
Node* right;
};
struct Tree
{
Node* root;
};
Tree createTree()
{
Tree tmp;
tmp.root = NULL;
return tmp;
}
void addToNode(Node* node, int value)
{
Node* tmp = new Node;
tmp->data = value;
tmp->left = NULL;
tmp->right = NULL;
if(node == NULL)
node = tmp;
else if(value >= node->data)
addToNode(node->right, value);
else
addToNode(node->left, value);
}
void add(Tree* tree, int value)
{
addToNode(tree->root, value);
}
int _tmain(int argc, _TCHAR* argv[])
{
Tree tree = createTree();
add(&tree, 10);
printf("%d", tree.root->data);
scanf("%*s");
return 0;
}
When you are passing your pointer into the function, you create a local version of the pointer. This local variable (node) does indeed point into the same memory that the outer pointer you were passing. However, any attempt to change this variable (not the memory it points to, but the pointer variable itself) will only change the local variable.
So your node points to the same memory location as your tree, but the node variable itself isn't equal to the tree variable, so your changes are not visible from the outer function.
It sounds complicated, sorry, but it's exacly the same thing as in this:
void foo( int a )
{
a++;
}
int main()
{
int var = 5;
foo( var );
std::cout << var;
}
Of course in this case the var will not change, it's the a that is being changed inside the function.
To fix the issue, pass a reference to the pointer instead of the pointer itself:
void addToNode(Node*& node, int value)
In the function addToNode when you assign to node, that assignment is not visible in the function calling addToNode because node is a local variable.
You should pass it as a reference instead:
void addToNode(Node*& node, int value)
{
...
}
Joachim already beat me to the answer, but I'll add this observation in anyway.
Your code leaks memory.
void addToNode(Node* node, int value)
{
Node* tmp = new Node;
tmp->data = value;
tmp->left = NULL;
tmp->right = NULL;
if(node == NULL)
node = tmp;
else if(value >= node->data)
addToNode(node->right, value);
else
addToNode(node->left, value);
}
Every call to addToNode creates a new Node instance in tmp, but if the parameter Node* node is not NULL, this new Node is not deleted and does not become accessible by the rest of the application.
There are a number of ways to avoid this. The simplest would be to check if node is NULL before creating a new instance.
Related
Today, I have learned about the Binary Search Tree, and I am trying to implement it, but I got a problem.
Assume that I have a Struct like this:
struct Node {
int v;
Node* left = NULL;
Node* right = NULL;
}
Below it, I have:
// At the beginning, root is NULL
Node* root = NULL;
Node* new_node(int v) {
Node* n = new Node;
n->v = v;
return n;
}
void insert(int v) {
// At the beginning, root is NULL
Node* c = root;
while (c != NULL) {
if (v < c->v) {
c = c->left;
} else {
c = c->right;
}
}
c = new_node(v);
}
And in the main code, I tested my implementation by using this code:
int main() {
insert(5);
}
When I use insert(5), in insert function, the variable c will be root, and because root at that time is NULL, so c will equal to new_node(v). But when I print root->v it returns nothing.
Did I make something wrong??
In your code you do not modify root after initialization. root is always NULL. This
Node* c = root;
// ...
c = new_node(v);
will not change root. It merely declares a local variable c, initializes it with the value of root and assigns a new value to it.
If you want to change the value of something inside a function you can pass it by reference, pointers are no different with respect to that. For example:
#include <iostream>
struct Node {
int v;
Node* left = NULL;
Node* right = NULL;
};
Node* root = NULL;
Node*& find_insertion(Node*& ptr, int v){
if (ptr == NULL) return ptr;
if (v < ptr->v) {
return find_insertion(ptr->left,v);
} else {
return find_insertion(ptr->right,v);
}
}
void insert_at(Node*& ptr,int v){
Node*& insertion = find_insertion(root,v);
insertion = new Node;
insertion->v = v;
}
void insert(int v){
insert_at(root,v);
}
int main() {
insert(5);
std::cout << root->v;
}
Next you should take a look at smart pointers (std::unique_ptr) to avoid leaks or compilcated manual memory managment.
I am implementing a number of LinkedList ADT's for my compsci class and I'm running into the same problem on every one. The code listed below is a binary tree ADT. The compiler gets lost when trying to input data into the new nodes. The code compiles without any errors, but the compiler does not return anything, I think it's stuck trying to find the pointer. I come from Java so I'm still working my way around pointers.
#include <iostream>
struct TreeNode {
//represents a single node in a binary tree of int data
int data; //immediate data
TreeNode *left; //left subtree
TreeNode *right; //right subtree
TreeNode(int in);
};
TreeNode::TreeNode(int in) {
data = in;
left = NULL;
right = NULL;
}
The compiler can't seem to find the pointer referenced in these two append functions.
void addLeft(TreeNode *root, int newData) {
TreeNode *new_node;
new_node->data = newData;
root->left = new_node;
}
void addRight(TreeNode *root, int newData) {
TreeNode *new_node;
new_node->data = newData;
root->right = new_node;
}
//counts nodes in binary tree from designated root point
int countNodes(TreeNode *root) {
if (!root) {
return 0; //empty tree
}
int count = 1;
count += countNodes(root->left); //adds left subtree nodes
count += countNodes(root->right); //adds right subtree countNodes
return count;
}
void preorderPrint(TreeNode *root) { //root first, then left, then right
if (root) {
std::cout << root->data << " ";
preorderPrint(root->left);
preorderPrint(root->right);
}
}
void postorderPrint(TreeNode *root) { //left first, then right, then root
if (root) {
postorderPrint(root->left);
postorderPrint(root->right);
std::cout << root->data << " ";
}
}
void inorderPrint(TreeNode *root) { //left first, then root, then right
if (root) {
inorderPrint(root->left);
std::cout << root->data << " ";
inorderPrint(root->right);
}
}
bool tree_contains(TreeNode *root, int item) {
if (!root) {
return false; //if the root doesn't exist, the tree doesn't exist
}
else if (root->data = item) {
return true; //item is found in the root node
}
else if (root->data > item) {
}
}
int main() {
TreeNode *root;
root->data = 5;
addLeft(root, 4);
addRight(root,9);
inorderPrint(root);
return 0;
}
Your root is not initialized. It currently has an undefined value. It should be:
TreeNode *root = new TreeNode(5);
... // Do whatever you want
// delete root and everything else.
A pointer is just a variable that holds an address of an object in memory. When you define a pointer like
int *foo;
you haven't initialized it, so its value is indeterminate. That means it doesn't hold a valid pointer value that could be used to access an object in memory. To make a pointer actually point to something, you have to assign it an address:
int bar;
inf *foo = &bar;
Now foo holds the address of bar and you can dereference foo to write to bar:
*foo = 42;
// bar is now 42
In your code
TreeNode *root;
root->data = 5;
You try to dereference (root->data is just syntactic sugar for (*root).data) a pointer root that hasn't been initialized with or assigned a valid pointer value.
Since you want to create a dynamic data structure that grows on demand, you want to allocate memory at runtime. You could do so using the new operator:
TreeNode *root = new TreeNode; // allocates an object of the type
// TreeNode
root->data = 5; // is now safe.
But since you provide a constructor for TreeNode that takes an int you can write:
TreeNode *root = new TreeNode{ 5 };
The same goes for many other locations in your code as well.
Please remember that dynamically allocated memory should be deallocated when it is no longer needed:
`delete root;`
Hello I have a problem to returned variable from my pop function.
I will be happy if you could help me.
The function receives a pointer to the top of the list and should return the answer but I have a problem with a pointer to the list and intger the answer.
Function Code -
int pop(Node* top)
{
Node* tmp = top;
int ans = tmp->next;
top = top->next;
delete tmp;
return ans;
}
Node -
struct Node
{
int num;
Node* next;
}
Node* top = new Node;
The line int ans = tmp->next; appears to be the source of the problem. This is attempting to take the next pointer in the node, convert it to an int, and return it. What you (almost certainly) want is to retrieve the data from the node and return that, with something like int ans = tmp->num;.
Of course, that's not saying the code is perfect otherwise (e.g., it seems to lack any attempt at checking for, not to mention dealing with, errors), but at least with that change, it stands some chance of working correctly under some (ideal) circumstances.
Usually such a function throws an exception if the stack is empty or it has undefined behaviour. I used return value 0 in case when the stack is empty.
int pop( Node * &top )
{
int value = 0;
if ( top )
{
value = top->num;
Node *tmp = top;
top = top->next;
delete tmp;
}
return value;
}
There is another approach when function poo has type void that is when it returns nothing but simply removes the element on the top.
As mentioned in my comment you should split this up to two separate functions. One to get the value, and another one to pop (remove) the Node
void pop(Node*& top) { // Note the reference. You want to change the current top node.
// ^
if ( top ) {
Node *tmp = top;
top = top->next;
delete tmp;
}
}
int& top(Node* top) {
if ( top ) {
return top->num;
}
// Throw an appropriate exception if the stack is empty
throw std::out_of_range("Stack is empty.");
}
First, you are trying to delete tmp node, but top node still exist and value has to be returned as ans or top->next or in this situation top->num. Why do you initialize node tmp in the function when node tmp is a parameter? Why should node * &top be in the function parameters instead of tmp.
value = top->num doesn't fix the problem, because he wants the pointer from the top of the linked list not the random node inputed through the function parameters. To fix this problem Node * tmp should equal top and then value should be equal to tmp->num. Otherwise all other problems have been fixed.
//EDIT
Ignore everything before //edit because all that is questions about his question that I now already know. I have compiled this code and it completely worked for me.
struct Node
{
int data;
Node *next;
};
int pop(Node *head)
{
while(head->next != NULL)
{
head = head->next;
}
int value;
Node *tmp;
tmp = new Node;
value = head->data;
tmp = head;
delete tmp;
return value;
}
Compiled code link - http://ideone.com/7EgBhf
I am working on unsorted linked list check full currently, below is my specification and implementation.
Specification:
#ifndef UNSORTEDLIST_H
#define UNSORTEDLIST_H
#include <iostream>
using namespace std;
struct Node {
float element;
Node* next;
};
class UnsortedList
{
public:
UnsortedList();
bool IsEmpty();
bool IsFull();
void ResetList();
void MakeEmpty();
int LengthIs();
bool IsInTheList(float item);
void InsertItem(float item);
void DeleteItem(float item);
float GetNextItem();
private:
Node* data;
Node* currentPos;
int length;
};
#endif
And implemetation:
UnsortedList::UnsortedList()
{
length = 0;
data = NULL;
currentPos = NULL;
}
bool UnsortedList:: IsEmpty(){
if(length == 0)
{
return true;
}
else
{
return false;
}
}
bool UnsortedList::IsFull(){
Node* ptr = new Node();
if(ptr == NULL)
return true;
else
{
delete ptr;
return false;
}
}
void UnsortedList::ResetList(){
currentPos = NULL;
}
void UnsortedList::MakeEmpty()
{
Node* tempPtr = new Node();
while(data != NULL)
{
tempPtr = data;
data = data->next;
delete tempPtr;
}
length = 0;
}
int UnsortedList::LengthIs(){
return length;
}
bool UnsortedList:: IsInTheList(float item){
Node* location = new Node();
location = data;
bool found = false;
while(location != NULL && !found)
{
if(item == location->element)
found = true;
else
location = location->next;
}
return found;
}
void UnsortedList:: InsertItem(float item){
Node* location = new Node();
location->element = item;
location->next=data;
data = location;
length++;
}
void UnsortedList:: DeleteItem(float item){
Node* location = data;
Node* tempPtr;
if(item == data->element){
tempPtr = location;
data = data->next;
}
else{
while(!(item == (location->next) ->element) )
location = location->next;
tempPtr = location->next;
location->next = (location->next)->next;
}
delete tempPtr;
length--;
}
float UnsortedList::GetNextItem(){
if(currentPos == NULL)
currentPos = data;
else
currentPos = currentPos->next;
return currentPos->element;
}
1.In the constructor, why don't assign currentPos as null?
2.In the IsInTheList function, Why points to pointer "next" ? Isn't next is a null pointer since it has been declared in struct as Node* next?
The pointer value is not set to NULL value by default, you should set to to null explicitly. Also instead of using NULL, choose using nullptr.
This code is rather incomplete, so it is difficult to answer your questions.
This does not contain the code to insert an item in the list, which is where I would expect both the next and currentPos pointers to be set. However, that's based on a number of assumptions.
However, I don't see where next is used in the "check full function" at all, so that question is a bit confusing.
I'll also point out that this code has a glaring memory leak. The first line in IsInTheList allocates memory for a new Node, which is immediately lost with location = data.
Pointers (like any other basic type) need to be initialized before use. A value of NULL is still a value.
The code you provided seems to be very incomplete. Is data supposed to be the head of your list? I am not sure how you define "fullness". If you want to test if the list is empty, you can see if your "head" of the list is null:
bool UnsortedList::IsEmpty() {
if (data == NULL) {return true;} // if there is no first element, empty
else {return false;} // if there is ANY element, not empty
}
Or more compactly:
bool UnsortedList::Empty() {
return (data == NULL);
}
When a node is added to a linked list, we usually add the node as a whole and modify the element that came before it. For example, we might create a new node and add it using code like the following:
// implementation file
void UnsortedList::InsertItem(const float& item) {
if (data == NULL) { // no elements in list, so new node becomes the head
data = new Node; // allocate memory for new node
data->element = item; // fill with requested data
data->next = NULL; // there is no element after the tail
}
else {
new_node = new Node; // allocate memory
new_node->element = item // set data
new_node->next = NULL; // new end of the list, so it points to nothing
tail->next = new_node; // have the OLD end node point to the NEW end
tail = new_node; // have the tail member variable move up
}
}
// driver file
int main() {
UnsortedList my_list;
float pie = 3.14159;
my_list.AddNode(pie);
return 0;
}
Please note that I made use of a Node* member variable called tail. It is a good idea to keep track of both where the list begins and ends.
In your IsFull function, it will always return false since it can always create a new Node*. Except perhaps if you run out of memory, which is probably more problematic.
Your functions are rather confusing and your pointer work leaves many memory leaks. You might want to review the STL list object design here.
typedef struct treeNode {
treeNode* left;
treeNode* right;
int data;
treeNode(int d) {
data = d;
left = NULL;
right = NULL;
}
}treeNode;
void insert(treeNode *root, int data) {
if (root == NULL) {
cout << &root;
root = new treeNode(data);
}
else if (data < root->data) {
insert(root->left, data);
}
else {
insert(root->right, data);
}
}
void inorderTraversal(treeNode* root) {
if (root == NULL)
return;
inorderTraversal(root->left);
cout<<root->data;
inorderTraversal(root->right);
}
int main() {
treeNode *root = new treeNode(1);
cout << &root << endl;
insert(root, 2);
inorderTraversal(root);
return 0;
}
So I'm pretty tired, but I was whipping some practice questions up for interview prep and for some reason this BST insert is not printing out that any node was added to the tree. Its probably something im glossing over with the pointers, but I can't figure it out. any ideas?
void insert(treeNode *root, int data) {
if (root == NULL) {
cout << &root;
root = new treeNode(data);
}
This change to root is lost as soon as the function ends, it does not modify the root passed as argument but its own copy of it.
Take note that when u insert the node, use pointer to pointer (pointer alone is not enough):
So, here is the fixed code:
void insert(treeNode **root, int data) {
if (*root == NULL) {
cout << root;
*root = new treeNode(data);
}
else if (data < (*root)->data) {
insert(&(*root)->left, data);
}
else {
insert(&(*root)->right, data);
}
}
And in main:
int main() {
treeNode *root = new treeNode(1);
cout << &root << endl;
insert(&root, 2);
inorderTraversal(root);
return 0;
}
Your logic is correct!
The only issue is that when you create a local variable, even if it is a pointer, its scope is local to the function. In your main:
...
insert(root, 2);
...
function call sends a copy of the root which is a pointer to treeNode (not the address of root). Please note that
void insert(treeNode *root, int data)
gets a treeNode pointer as an argument (not the address of the pointer). Attention: This function call may look like "call by pointer" (or reference) but it is actually "call by value". The root you define in the main function and the root inside the insert method have different addresses in the stack (memory) since they are different variables. The former is in main function stack in the memory while the latter is in insert method. Therefore once the function call insert finishes executing, its stack is emptied including the local variable root. For more details on memory refer to: stacks/heaps.
Of course the data in the memory that you allocated using:
*root = new treeNode(data);
still stays in the heap but you have lost the reference to (address of) it once you are out of the insert function.
The solution is either passing the address of original root to the function and modifying it (as K-ballo and dip has suggested) OR returning the modified local root from the function. For the first approach please refer to the code written by dip in his/her answer.
I personally prefer returning the modified root from the function since I find it more convenient especially when implementing other common BST algorithms. Here is your function with a slight modification of your original code:
treeNode* insert(treeNode *root, int data) {
if (root == NULL) {
root = new treeNode(data);
}
else if (data < root->data) {
root->left=insert(root->left, data);
}
else {
root->right=insert(root->right, data);
}
return treeNode;
}
The function call in main will be:
int main() {
treeNode *root = new treeNode(1);
cout << &root << endl;
root = insert(root, 2);
inorderTraversal(root);
return 0;
}
Hope that helps!
After a while seeing some complicated methods of dealing with the Binary tree i wrote a simple program that can create, insert and search a node i hope it will be usefull
/*-----------------------Tree.h-----------------------*/
#include <iostream>
#include <queue>
struct Node
{
int data;
Node * left;
Node * right;
};
// create a node with input data and return the reference of the node just created
Node* CreateNode(int data);
// insert a node with input data based on the root node as origin
void InsertNode (Node* root, int data);
// search a node with specific data based on the root node as origin
Node* SearchNode(Node* root, int data);
here we define the node structure and the functions mentioned above
/*----------------------Tree.cpp--------------*/
#include "Tree.h"
Node* CreateNode(int _data)
{
Node* node = new Node();
node->data=_data;
node->left=nullptr;
node->right=nullptr;
return node;
}
void InsertNode(Node* root, int _data)
{
// create the node to insert
Node* nodeToInsert = CreateNode(_data);
// we use a queue to go through the tree
std::queue<Node*> q;
q.push(root);
while(!q.empty())
{
Node* temp = q.front();
q.pop();
//left check
if(temp->left==nullptr)
{
temp->left=nodeToInsert;
return;
}
else
{
q.push(temp->left);
}
//right check
if(temp->right==nullptr)
{
temp->right=nodeToInsert;
return;
}
else
{
q.push(temp->right);
}
}
}
Node* SearchNode(Node* root, int _data)
{
if(root==nullptr)
return nullptr;
std::queue<Node*> q;
Node* nodeToFound = nullptr;
q.push(root);
while(!q.empty())
{
Node* temp = q.front();
q.pop();
if(temp->data==_data) nodeToFound = temp;
if(temp->left!=nullptr) q.push(temp->left);
if(temp->right!=nullptr) q.push(temp->right);
}
return nodeToFound;
}
int main()
{
// Node * root = CreateNode(1);
// root->left = CreateNode(2);
// root->left->left = CreateNode(3);
// root->left->left->right = CreateNode(5);
// root->right = CreateNode(4);
// Node * node = new Node();
// node = SearchNode(root,3);
// std::cout<<node->right->data<<std::endl;
return 0;
}