How to add a node in Binary search tree? - data-structures

struct node {
int data{};
node *right{nullptr};
node *left{nullptr};
};
class BTree {
private:
node *root;
void insert(node *sr, int num);
public:
BTree();
void buildTree(int num);
};
void BTree::insert(node *sr, int num) {
if (sr == nullptr) {
sr = new node;
sr->data = num;
} else {
if (num < sr->data)
insert(sr->left, num);
else
insert(sr->right, num);
}
}
int main() {
BTree tree;
tree.buildTree(3);
return 0;
}
I am using the above insert method to add a node to Binary Search Tree. But this method is unable to add the node , if i add a number as its root or first node the root remains nullptr.
How do i resolve this issue.

At the first root is nullptr , and I am sending root i.e the nullptr as the argument. As nullptr does refer to any node therefor the root is not getting updated by the operation in the method.
possible solution:
use pointer to pointer, so that address of the node can be passed and and changed.
directly acces the root to do changes.
PROTOTYPE
void insert(node **sr, int num);
BUILD TREE METHOD
void BTree::buildTree(int num) {
insert(&root, num);
}
INSERT METHOD
void BTree::insert(node **sr, int num) {
if (*sr == nullptr) {
*sr = new node;
(*sr)->data = num;
} else {
if (num < (*sr)->data)
insert(&((*sr)->left), num);
else
insert(&((*sr)->right), num);
}
}

Related

Binary search tree function definition error

This is the part of code where I want the createNode function to return the node that it creates.
struct Node *ptr = createNode(key);
if(key<prev->data)
{
prev->left = ptr;
}
else
{
prev->right = ptr;
}
createNode Function :-
Node * tree :: createNode(int key). //Unknown type name 'Node'
{
Node * n = new Node;
n->data = key;
n->left = NULL;
n->right = NULL;
return n;
}
declaration of function in class:-
Node * createNode(int key);
structure of Node :-
struct Node
{
int data;
Node *left;
Node *right;
};
when I define the function createNode i'am getting the error that -> Unknown type name 'Node'
how can I define the function whose return type is pointer.
#include <iostream>
#include<stdlib.h>
using namespace std;
class tree
{
struct Node
{
int data;
Node *left;
Node *right;
};
public:
Node * toDelete(Node *root, int key);
void insert(Node *root,int key);
Node * createNode(int key);
int isBST(Node* root);
void preorder(Node *root);
void postorder(Node *root);
void inorder(Node *root);
Node * search(Node *root,int key);
Node * searchIter(Node *root,int key);
Node * findmin(Node *root);
};
void tree :: preorder(Node *root)
{
if(root != NULL)
{
cout<<root->data<<"\t";
preorder(root->left);
preorder(root->right);
}
}
void tree :: postorder(Node *root)
{
if(root!=NULL)
{
postorder(root->left);
postorder(root->right);
cout<<root->data<<"t";
}
}
void tree :: inorder(Node *root)
{
if(root!=NULL)
{
inorder(root->left);
cout<<root->data<<"\t";
inorder(root->right);
}
}
void tree :: insert(Node *root,int key)
{
struct Node *prev = NULL;
while(root!=NULL)
{
prev = root;
if(key<root->data)
{
root = root->left;
}
else
{
root = root->right;
}
}
struct Node *ptr = createNode(key);
if(key<prev->data)
{
prev->left = ptr;
}
else
{
prev->right = ptr;
}
}
Node * tree :: createNode(int key) //Unknown type name 'Node'
{
Node * n = new Node;
n->data = key;
n->left = NULL;
n->right = NULL;
return n; //Cannot initialize return object of type 'int *' with an lvalue of type 'tree::Node *'
}
int main()
{
}
Keep Node outside tree class.
struct Node
{
int data;
Node* left;
Node* right;
};
class tree
{
....
Node is private to your tree class. Hence, it is not directly accessible outside the class the way you are trying in your code.

preorder traversal using stack

i'm trying to implement binary tree, pre order traversal using stack.
here its popping the last left node and after that root=root->right doesnt seem to work. Pls help. here 7 is being popped out and is being displayed and after the the program is ending.
all the functions are working yet not the desired output
#include<stdio.h>
#include<stdlib.h>
#define maxsize 100
int a[maxsize];
int top=-1;
struct node{
int data;
struct node *left, *right;
};
struct node *newNode(int data)
{
struct node *nn;
nn=(struct node *)malloc(sizeof(struct node));
if(!nn)
return;
nn->data=data;
nn->left=nn->right=NULL;
return nn;
};
void push(struct node *root)
{
printf("pushcalled\n");
if(top!=maxsize-1)
a[++top]=root;
}
int isempty()
{
return(top==-1);
}
struct node *pop()
{
printf("popcalled\n");
if(top!=-1)
{
return a[top];
top--;
}
}
void deleteStack()
{
free(a[top--]);
}
void preorder(struct node *root)
{
while(1)
{
while(root)
{
printf("%d\t",root->data);
push(root);
root=root->left;
}
printf("hello\n");
if(isempty())
break;
printf("hello\n");
root=pop();
printf("Popped data is:%d\n",root->data);
root=root->right;
printf("right data is:%d\n",root->data);
}
deleteStack();
}
int main()
{
int data;
struct node *root=newNode(10);
root->left = newNode(11);
root->left->left = newNode(7);
root->right = newNode(9);
root->right->left = newNode(15);
root->right->right = newNode(8);
preorder(root);
return 0;
}
Your logic is correct but there are some errors in your code.
root=root->right;
printf("right data is:%d\n",root->data);
you should check whether the root is null or not before you try to access root->data. That is why you are getting a segmentation fault. So put a condition if(root!=NULL) above printf() statement.
Another mistake is in the implementation of stack's pop.
struct node *pop()
{
printf("popcalled\n");
if(top!=-1)
{
return a[top];
top--;
}
}
it should be like this,
struct node *pop()
{
printf("popcalled\n");
if(top!=-1)
{
struct node* temp = a[top];
top--;
return temp;
}
}
In your code, when you return a[top]; the line below it i.e. top--; never executes and the value of top remains same.

Reversing singly linked list using recursion

I have written code to reverse singly linked list using recursion. It is working fine on lists of length less than or equal to 174725. But on lists of length greater than 174725 it gives a segmentation fault(Segmentation fault: 11) while reversing it via reverse() call. Can someone please explain this to me ?
#include <iostream>
using namespace std;
class Node
{
public:
int val;
Node *next;
};
class Sll
{
public:
Node *head;
private:
void reverse(Node *node);
public:
Sll();
void insert_front(int key);
void reverse();
void print();
};
void Sll::reverse(Node *node)
{
if (node == NULL) return;
Node *rest = node->next;
if (rest == NULL)
{
head = node;
return;
}
reverse(rest);
rest->next = node;
node->next = NULL;
return;
}
Sll::Sll()
{
head = NULL;
}
void Sll::insert_front(int key)
{
Node *newnode = new Node;
newnode->val = key;
newnode->next = head;
head = newnode;
return;
}
void Sll::print()
{
Node *temp = head;
while (temp)
{
temp = temp->next;
}
cout << endl;
return;
}
void Sll::reverse()
{
reverse(head);
return;
}
int main()
{
Sll newList = Sll();
int n;
cin >> n;
for (int i = 0; i < n; i++) newList.insert_front(i + 1);
newList.reverse();
// newList.print();
return 0;
}
List reversing function must be tail-recursive, otherwise it is going to overflow the stack when recursing over a long list, like you observe. Also, it needs to be compiled with optimisations enabled or with -foptimize-sibling-calls gcc option.
Tail-recursive version:
Node* reverse(Node* n, Node* prev = nullptr) {
if(!n)
return prev;
Node* next = n->next;
n->next = prev;
return reverse(next, n);
}
An iterative list reversion can be more easily inlined though and it does not require any optimization options:
inline Node* reverse(Node* n) {
Node* prev = nullptr;
while(n) {
Node* next = n->next;
n->next = prev;
prev = n;
n = next;
}
return prev;
}

Lowest Common Ancestor of a Binary Search Tree code doesn't pass

can anyone help me with this code? I cannot figure out where I'm blocked.
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
TreeNode* res=NULL;
int i=0;
postTrav(root,p,q,res,i);
return res;
}
void postTrav(TreeNode* root, TreeNode* p, TreeNode* q,TreeNode* res,int& i){
if(!root){
return;
}
postTrav(root->left,p,q,res,i);
postTrav(root->right,p,q,res,i);
if(root==p||root==q){
i++;
}
if(i==2){
res=root;
i++;
}
}
You may have a logic bug in addition to this, but, because C [I assume] is call-by-value, setting res and i are changed local to a given function invocation, but then discarded. You'll need to pass around some addresses, as below. Especially, note that res is now TreeNode ** in postTrav.
TreeNode *
lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q)
{
TreeNode *res = NULL;
int i = 0;
postTrav(root, p, q, &res, &i);
return res;
}
void
postTrav(TreeNode *root, TreeNode *p, TreeNode *q, TreeNode **res, int *i)
{
if (!root) {
return;
}
postTrav(root->left, p, q, res, i);
postTrav(root->right, p, q, res, i);
if (root == p || root == q) {
*i++;
}
if (*i == 2) {
*res = root;
*i++;
}
}
UPDATE:
The above code is fine. But, whenever, I have a function that needs to return or maintain two or more values [in parallel], a technique I use is to create an additional "traversal" or "helper" struct that simplifies the argument passing.
If you needed an additional variable that needed to be modified/maintained across the calls, instead of adding an additional argument to all functions, it becomes easy/easier to just add another variable to the struct. This works particularly well when you're building up your logic as you go along.
Here's the code for the refinement. Notice that fewer arguments need to be pushed/popped. And, this probably executes as fast or faster than the original. Also, for me, trav->res seems a bit cleaner than *res
// traversal "helper" struct
struct _traverse {
TreeNode *p; // not modified
TreeNode *q; // not modified
TreeNode *res; // result
int i; // depth
// add more variables here as desired ...
#ifdef WANT_TRAVERSAL_STATISTICS
int visited_count; // number of nodes we visited
#endif
};
typedef struct _traverse Traverse;
TreeNode *
lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q)
{
Traverse trav;
trav.p = p;
trav.q = q;
trav.res = NULL;
trav.i = 0;
#ifdef WANT_TRAVERSAL_STATISTICS
trav.visited_count = 0;
#endif
postTrav(root, &trav);
#ifdef WANT_TRAVERSAL_STATISTICS
printf("Visited %d Nodes\n",trav.visited_count);
#endif
return trav.res;
}
void
postTrav(TreeNode *root, Traverse *trav)
{
if (!root) {
return;
}
#ifdef WANT_TRAVERSAL_STATISTICS
trav->visited_count += 1;
#endif
postTrav(root->left, trav);
postTrav(root->right, trav);
if (root == trav->p || root == trav->q) {
trav->i++;
}
if (trav->i == 2) {
trav->res = root;
trav->i++;
}
}
You are not using the property of BST. postTrav should be like this:
TreeNode* postTrav(TreeNode* root, TreeNode* p, TreeNode* q,)
{
if (root == NULL||p==NULL||q==NULL) return NULL;
int n1=p->data;
int n2=q->data;
while (root != NULL)
{
// If both n1 and n2 are smaller than root, then LCA lies in left
if (root->data > n1 && root->data > n2)
root = root->left;
// If both n1 and n2 are greater than root, then LCA lies in right
else if (root->data < n1 && root->data < n2)
root = root->right;
else break;
}
return root;
}

C++ Linked list insert back

I am trying to create a function that will insert a node to the back of the list using linked list. I am new to using linked list and I have tried many different ways of doing an insertion at the end of the list but nothing seems to be working. The main passes the values one at a time to be inserted 2 4 5 8 9, and the output is 2 0 0 0 0. I do not whats causing this problem.
.h
class Node
{
public:
Node() : data(0), ptrToNext(NULL) {}
Node(int theData, Node *newPtrToNext) : data(theData), ptrToNext(newPtrToNext){}
Node* getPtrToNext() const { return ptrToNext; }
int getData() const { return data; }
void setData(int theData) { data = theData; }
void setPtrToNext(Node *newPtrToNext) { ptrToNext = newPtrToNext; }
~Node(){}
private:
int data;
Node *ptrToNext; //pointer that points to next node
};
class AnyList
{
public:
AnyList();
//default constructor
void print() const;
//Prints all values in the list.
void destroyList();
//Destroys all nodes in the list.
~AnyList();
//destructor
int getNumOfItems();
void insertBack(int b);
void deleteFirstNode();
private:
Node *ptrToFirst; //pointer to point to the first node in the list
int count; //keeps track of number of nodes in the list
};
.cpp
void AnyList::insertBack(int b)
{
Node *temp = new Node;
if (ptrToFirst == NULL)
{
temp->setData(b);
ptrToFirst = temp;
}
else
{
Node *first = ptrToFirst;
while (first->getPtrToNext() != NULL)
{
first = first->getPtrToNext();
}
first->setPtrToNext(temp);
}
}
First, you really should be using the std::list or std::forward_list class instead of implementing the node handling manually:
#include <list>
class AnyList
{
public:
void print() const;
//Prints all values in the list.
void destroyList();
//Destroys all nodes in the list.
int getNumOfItems() const;
void insertBack(int b);
void deleteFirstNode();
private:
std::list<int> nodes; //nodes in the list
};
void AnyList::print() const
{
for (std::list<int>::const_iterator iter = nodes.begin(); iter != nodes.end(); ++iter)
{
int value = *iter;
// print value as needed...
}
}
void AnyList::destroyList()
{
nodes.clear();
}
void AnyList::getNumOfItems() const
{
return nodes.size();
}
void AnyList::insertBack(int b)
{
nodes.push_back(b);
}
void AnyList::deleteFirstNode()
{
if (!nodes.empty())
nodes.pop_front();
}
That being said, your manual implementation fails because you are likely not managing the nodes correctly (but you did not show everything you are doing). It should look something like this:
class Node
{
public:
Node() : data(0), ptrToNext(NULL) {}
Node(int theData, Node *newPtrToNext) : data(theData), ptrToNext(newPtrToNext) {}
~Node() {}
Node* getPtrToNext() const { return ptrToNext; }
int getData() const { return data; }
void setData(int theData) { data = theData; }
void setPtrToNext(Node *newPtrToNext) { ptrToNext = newPtrToNext; }
private:
int data;
Node *ptrToNext; //pointer that points to next node
};
class AnyList
{
public:
AnyList();
//default constructor
~AnyList();
//destructor
void print() const;
//Prints all values in the list.
void destroyList();
//Destroys all nodes in the list.
int getNumOfItems() const;
void insertBack(int b);
void deleteFirstNode();
private:
Node *ptrToFirst; //pointer to point to the first node in the list
Node *ptrToLast; //pointer to point to the last node in the list
int count; //keeps track of number of nodes in the list
};
AnyList:AnyList()
: ptrToFirst(NULL), ptrToLast(NULL), count(0)
{
}
void AnyList::print() const
{
for (Node *temp = ptrToFirst; temp != NULL; temp = temp->getPtrToNext())
{
int value = temp->getData();
// print value as needed...
}
}
AnyList::~AnyList()
{
destroyList();
}
void AnyList::destroyList()
{
Node *temp = ptrToFirst;
ptrToFirst = ptrToLast = NULL;
count = 0;
while (temp != NULL)
{
Node *next = temp->getPtrToNext();
delete temp;
temp = next;
}
}
int AnyList::getNumOfItems() const
{
return count;
}
void AnyList::insertBack(int b)
{
Node *temp = new Node(b, NULL);
if (ptrToFirst == NULL)
ptrToFirst = temp;
if (ptrToLast != NULL)
ptrToLast->setPtrToNext(temp);
ptrToLast = temp;
++count;
}
void AnyList::deleteFirstNode()
{
if (ptrToFirst == NULL)
return;
Node *temp = ptrToFirst;
ptrToFirst = temp->getPtrToNext();
if (ptrToLast == temp)
ptrToLast = NULL;
delete temp;
--count;
}

Resources