Pointer of struct changes - c++

#include<stack>
#include<iostream>
class Tree{
private:
struct tree{
int val;
tree * lChild;
tree * rChild;
tree * Parent;
};
tree *root;
public:
Tree();
void insert(int x);
};
Tree::Tree(){
root = NULL;
std::cout<<"ROOT inside constructor : "<<root<<std::endl;
}
void Tree::insert(int x){
tree *wst;
wst->val = x;
wst->lChild = NULL;
wst->rChild = NULL;
tree *temp = root;
tree *p = NULL;
std::cout<<"ROOT inside insert : "<<root<<std::endl;
while(temp != NULL){
p = temp;
if(x < temp->val)
temp = temp->lChild;
else
temp = temp->rChild;
}
std::cout<<x<<std::endl;
wst->Parent = p;
if(p == NULL){
root = wst;
}
else{
if(x < p->val)
p->lChild = wst;
else
p->rChild = wst;
}
}
int main(){
Tree tree;
tree.insert(404);
}
I want to check if pointer root is equal to NULL, but it does not seems too work. It seems like the pointer changes from 0 to 0x4 when I am inside the method insert. How can I check if pointer of struct is equal NULL?
EDIT In the insert method if tree doesn't have any nodes it should not enter first while loop, as root should be equall NULL. And my problem is that it enters this loop anyway and crashes when it checks for temp childrens(that are still not defined).

What does wst point to?
tree *wst;
wst->val = x;
wst->lChild = NULL;
wst->rChild = NULL;
// [...]
wst->Parent = p;
Whoops! Your program has undefined behaviour. No wonder it crashes. :)
You probably need tree* wst = new tree(); there. Don't forget to delete your nodes in the Tree destructor, too!
And I'd advise against having a type Tree plus a type tree; perhaps call the latter Node instead?

Related

I wanted to implement a BST and tried using vector for input

I wanted to implement a BST class with a vector and somehow its not working. I just wanted to know the reason why its not working.
The main reason that I can think of that root in the BST always remain NULL.
I wanted to experiment ways to use classes in data structures.
#include<iostream>
#include<vector>
using namespace std;
class Node{
public:
int data;
Node* left ;
Node* right ;
Node(int val){
data = val;
left = NULL;
right = NULL;
}
};
class BST{
public:
Node* root = NULL;
void insert(Node* r,int data){
Node* new_node = new Node(data);
if(r == NULL){
r = new_node;
}
if(data < r->data){
if(r->left == NULL){
r->left = new_node;
}
else{
insert(r->left,data);
}
}else if(data > r->data){
if(r->right == NULL){
r->right = new_node;
}
else{
insert(r->right,data);
}
}else{
return;
}
return;
}
BST(vector<int> bst_array){
for(int i = 0; i<bst_array.size(); i++){
insert(root,bst_array[i]);
}
}
void print_t(Node* r){
if(r == NULL){
cout<<"NULL";
return;
}
else{
print_t(r->left);
cout<<r->data<<" ";
print_t(r->right);
}
}
};
int main(){
vector<int> v = {1,3,5,44,23,78,21};
BST* tr = new BST(v);
tr->print_t(tr->root);
return 0;
}
There seem to be a logical mistake on my end please help me find it.
Thanks in advance.
The reason is that root is never assigned another value after its initialisation to NULL. Passing root as argument to the insert method can never alter root itself, as it is not the address of root that is passed, but its value.
Some other remarks:
insert always starts by creating a new node, at every step of the recursion. This is a waste of node creation. In the end you just need one new node, so only create it when its position in the tree has been identified.
The final else is not needed, as all it does is execute a return, which it would have done anyway without that else block
As insert is a method of BST, it is a pity that it requires a node as argument. You would really like to just do insert(data) and let it take care of it. For that to happen I suggest to move your insert method to the Node class, where the this node takes over the role of the argument. Then the BST class could get a wrapping insert method that forwards the job to the other insert method.
Instead of NULL use nullptr.
To solve the main issue, there are many solutions possible. But after making the above changes, it is quite easy to assign to root in the simplified insert method on the BST class.
Here is how it could work:
class Node{
public:
int data;
Node* left ;
Node* right ;
Node(int val){
data = val;
left = nullptr;
right = nullptr;
}
void insert(int data) {
if (data < this->data) {
if (this->left == nullptr) {
this->left = new Node(data);
} else {
this->left->insert(data);
}
} else if (data > this->data) {
if (this->right == nullptr) {
this->right = new Node(data);
} else {
this->right->insert(data);
}
}
}
};
class BST {
public:
Node* root = nullptr;
void insert(int data) {
if (root == NULL) { // Assign to root
root = new Node(data);
} else { // Defer the task to the Node class
root->insert(data);
}
}
BST(vector<int> bst_array){
for(int i = 0; i<bst_array.size(); i++){
insert(bst_array[i]); // No node argument
}
}
/* ...other methods ...*/
}

Try tree inplementation

Try to make tree , have a some troubles, first it's print function - it's print not integers that i put, but print random numbers;
Another trouble its append child - its works only one times;
Will be happy if you will help me with this task.
And also give some good articles about linked lists, trees on c and c++;
#include <iostream>
#include <stdio.h>
using namespace std;
struct Node
{
void* m_pPayload;
Node* m_pParent;
Node* m_Children;
};
struct Person
{
int m_Id;
};
//typedef bool (*NodeComparator)(void* pValue, void* pPayload);
/*bool Comp(void* pValue, void* pPayload)
{
Person* pVal = (Person*)pValue;
Person* pPay = (Person*)pPayload;
if (pVal->m_Id == pPay->m_Id)
return true;
else
return false;
}
*/
Node* NewNode(void* pPayload)
{
Node* pNode = new Node;
pNode->m_pParent = nullptr;
pNode->m_Children = 0;
pNode->m_pPayload = pPayload;
return pNode;
}
Person* NewPerson(int id)
{
Person* p = new Person;
p->m_Id = id;
return p;
}
//Node* FindNode(Node* pParent, Node* m_pPayload, NodeComparator comparator);
void AppendChild(Node* pParent, Node* pNode)
{
if (pParent->m_Children == NULL)
pParent->m_Children = pNode;
}
void print(Node* head)
{
Node* current_node = head;
while (current_node != NULL)
{
printf("%d\n ", current_node->m_pPayload);
current_node = current_node->m_Children;
}
}
int main()
{
Node* T = new Node;
T = NewNode(NewPerson(5));
AppendChild(T, NewNode(NewPerson(11)));
AppendChild(T, NewNode(NewPerson(15)));
print(T);
}
printf("%d\n ", current_node->m_pPayload)
is incorrect. %d wants an integer and it's being given a pointer. The results will be unusual, and likely appear to be random garbage.
printf("%d\n ", ((Person*)current_node->m_pPayload)->m_Id);
^ ^
| Get id from Person
treat payload pointer as pointer to Person
will solve the immediate problem.
Your code actually seems to be pretty messed up with a lot of things going on, here sharing my own commented code from few years back, hope it helps
#include <bits/stdc++.h>
using namespace std;
// Single node representation
struct node {
int data;
node *left, *right;
};
// Declaring temp for refference and root to hold root node
node *root, *temp;
// This function only generates a node and return it to the calling function with data stored in it
node* generateNode(int data){
temp = new node();
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// This function actually adds node to the tree
node* addNode(int data, node *ptr = root){
// If the node passed as ptr is NULL
if(ptr == NULL){
ptr = generateNode(data);
return ptr;
}
// Condition to check in which side the data will fit in the tree
else if(ptr->data < data)
//if its in right, calling this function recursively, with the right part of the tree as the root tree
ptr->right = addNode(data, ptr->right);
else
//In case the data fits in left
ptr->left = addNode(data, ptr->left);
//Note: if there is no data in left or roght depending on the data's valid position, this function will get called with NULL as second argument and then the first condition will get triggered
//returning the tree after appending the child
return ptr;
}
//Driver function
int main ()
{
int c, data;
for (;;){
cin >> c;
switch(c){
case 1:
cout << "enter data: ";
cin >> data;
//Updating root as the tree returned by the addNode function after adding a node
root = addNode(data);
break;
default:
exit(0);
break;
}
}
return 0;
}
Please find below a piece of code that should easily get you started. It compiles and it traverse the tree using recursion.
#include <iostream>
#include <vector>
#include <stdio.h>
using namespace std;
struct Node
{
int m_Id;
vector<Node*> m_Children;
Node(const int& id){
m_Id = id;
}
void AppendChild(Node* pNode) {
m_Children.push_back(pNode);
}
void Print() {
printf("%d\n ", m_Id);
}
};
void traverse(Node* head)
{
Node* current_node = head;
current_node->Print();
for(int i = 0; i<current_node->m_Children.size(); i++) {
traverse(current_node->m_Children[i]);
}
}
int main()
{
Node* T0 = new Node(0);
Node* T10 = new Node(10);
T10->AppendChild(new Node(20));
Node* T11 = new Node(11);
Node* T12 = new Node(12);
Node* T22 = new Node(22);
T22->AppendChild(new Node(33));
T12->AppendChild(T22);
T0->AppendChild(T10);
T0->AppendChild(T11);
T0->AppendChild(T12);
traverse(T0);
}
First for printing the node value
Talking about the current mistake that you had committed is in the above code is:
You have not mentioned its pointer to its child (specifically right or left). Due to which it is showing garbage value every time.
For e.g.: print( node->left);
Since you need to type caste it properly to show the data of data.
For e.g.: printf("%d\n ", ((Person*)current_node->m_pPayload)->m_Id);
There is a specific direction in which you want to print data. For trees, there are three directions in which you can print the data of the node and they are as follow:
Left order or Inorder traversal
Preorder traversal
Postorder traversal
This can give you better information about traversal.
Secondly for adding the node to a tree
This might help explain it better.

Binary Search Tree shows empty

struct node
{
int data;
node *left,*right;
};
class bst
{
public:
node *root;
bst(){root = NULL;}
void bst_insert(node*,int);
void inorder(node*);
};
void bst::bst_insert(node* x, int d) {
if (x== NULL) {
node* tmp = new node;
tmp->data = d;
tmp->left = NULL;
tmp->right = NULL;
x= tmp;
}
else if (d <= x->data)
bst_insert(x->left,d);
else
bst_insert(x->right,d);
}
void bst::inorder(node* x) {
if(x != NULL) {
inorder(x->left);
cout << x->data << " ";
inorder(x->right);
}
}
int main() {
bst b;
b.bst_insert(b.root,3);
b.bst_insert(b.root,2);
b.inorder(b.root);
}
bst is a class with member node* root (initialize with null on constructor)
Binary Search Tree display in order always shows empty.
What is wrong with the code ?
the code seems fine, but always bst has no value and always show empty, and root is null !!!
No code anywhere sets root to anything other than NULL. When you call inorder, it does nothing since root is NULL.
b.bst_insert(b.root,3);
Since root is NULL at first, this is equivalent to:
b.bst_insert(NULL,3);
This doesn't attach the newly-created node to anything.

Binary search tree traversal

Hi guys I have a doubt in inserting a new node in BST. In the addNode module I am trying to insert an element in the BST, but each time while adding a new node it is adding to the same root node which I passed from main function initially without traversing inside the tree.
This is the code which I have written.
#include<stdio.h>
#include<stdlib.h>
#include<cstdio>
#include<iostream>
using namespace std;
struct node
{
int data;
struct node *left;
struct node *right;
};
struct node* newNode(int data)
{
node* temp = (node*)malloc(sizeof(struct node));
//struct temp = new node;
temp->data = data;
temp->left = NULL;
temp->right = NULL;
return(temp);
};
int addNode(node *dest, node *root)
{
if(root == NULL)
{
cout<<"adding data to node for "<< dest->data<<endl;
root = dest;
cout<<"ROOT VALUE = root->data "<<root->data<<endl;
return 1;
}
if(dest->data > root->data)
{
cout<<"Traverse right for "<<dest->data<<endl;
addNode(dest, root->right);
}
else if(dest->data < root->data)
{
cout<<"Traverse left for "<<dest->data<<endl;
addNode(dest, root->left);
}
}
void printNodes(node *root)
{
if(root != NULL)
{
printNodes(root->left);
if(root->left != NULL && root->right != NULL)
std::cout<< root->data <<" ";
printNodes(root->right);
}
}
int main()
{
int i, j, k, flag;
int arr[6] = {4, 2,8, 1, 0, 10};
node *start = newNode(arr[0]);
for(i = 1; i < 6; i++)
{
node *newOne = newNode(0);
newOne->data = arr[i];
cout<<"NODE DATA - start->data "<<start->data;
if(addNode(newOne, start))
std::cout<<"\nNode added"<<endl;
}
printNodes(start);
return 1;
}
I am quite new to trees concept as well as pointers concept in trees. Any help is appreciated and thank you.
... but each time while adding a new node it is adding to the same root
node
This is because you are adding it always to the same root, as here
if(addNode(newOne, start))
start is always the same. You could make addNode return the new root and call it like that:
start = addNode(newOne,start);
I'll leave it to you to implement it.
Note that parameters are always passed by value in c++ (unless you pass-by-reference), thus changing the parameter inside the method, root = dest;, has no effect on the start in main.

Can't insert a new node in the binary tree

I believe my insertion function is right, but it looks like the new node is not being inserted in the tree. I could not figure out where is the mistake. I appreciate any help,thanks.
There is the declaration of node and tree:
class Node{
int key;
Node *right, *left;
}
class Tree{
public:
int init();
Node *root;
Node *insert(int key, Node *p);
};
there is the functions:
int Tree::init(){
this->root = NULL; return 1;
}
Node *Tree::insert(int key, Node *p){
if(p == NULL){
Node *novo = new Node();
novo->key = key;
novo->left = NULL;
novo->right = NULL;
p = novo;
}
else if(key < p->key){ p->left = insert(key, p->left); }
else if(key > p->key){ p->right = insert(key, p->right); }
else{ cout << "Error: key already exist" << endl; }
return p;
}
When I call the function in the main, it looks like it does not link the new node
int main() {
Tree dictionary;
cout << "enter the key"; cin >> key;
dictionary.insert(key, dictionary.root);
cout << dictionary.root->key;
}
In your insert() function, when the tree is empty or if you've reached the last node, you create a new node:
if(p == NULL){
Node *novo = new Node();
novo->key = key;
novo->left = NULL;
novo->right = NULL;
p = novo; // ouch !!!!
}
Unfortunately, the statement p=novo only updates the local parameter p of your function. Its value will vanish as soon as you return from the function. It will not update the pointer with which you've called your function. So the root of your tree remains NULL (or the left/right pointer of the last node).
To get the effect that you expect (i.e. your p assigment updates the root pointer or the pointer to left/right of the last node), you need to change the signature to:
Node *insert(int key, Node *& p); // p is passed by reference
This will pass the pointer p by reference. Modifying p will then have the effect of modifying the pointer you used to call the function, and will endure a lasting effect of the insertion.