getting runtime error when accessing node through the queue - binary-tree

i am trying to connect the nodes of a binary tree that are at the same level
i am using a queue to do it. initially i have pushed the root into queue. but in line 12 when the first if statement is executed that is
if(q.front()->left!=NULL) then i am getting a runtime error.
please help
node structure:
struct node
{
int data;
struct node* left;
struct node* right;
struct node* nextRight;
};
function to connect the nodes
node* connect(node* root)
{
if(root=NULL)
return display(root);
queue<node*> q;
int count=0;
q.push(root);
count++;
while(!q.empty())
{
cout << "inside while loop\n";
int i=1,temp=0;
while(i<=count)
{
cout << "inside inner while\n";
if(q.front()->left!=NULL)
{
cout << "inside if 1\n";
q.push(q.front()->left);
temp++;
}
if(q.front()->right!=NULL)
{
cout << "inside if 2\n";
q.push(q.front()->right);
temp++;
}
node* v=q.front();
q.pop();
if(i==count)
v->nextRight=NULL;
else
v->nextRight=q.front();
}
count=temp;
}
return display(root);
}

You need to make lot of changes in your code.
Mistake 1:
while(i<=count)
will never be true.
Mistake 2:
v->nextRight=q.front();
will set the nextRight to point to Left child.
Mistake 3:
i is never changing, then why declare a variable and create confusion.

Related

How to add a node in Binary search tree?

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);
}
}

Breadth First Search algorithm variation

so i am new to this programming and i had a doubt on this part of learning it , for two variation problems nearly the code is similar with a little bit of change but i dont understand it clearly.
The Node class type is a standard Tree based structure along with a next self-referential
Connect level order siblings:
class Solution {
public:
Node* connect(Node* root) {
return helper(root);
}
Node* helper(Node* root)
{
if(root==NULL)
return root;
queue<Node*>queue;
queue.push(root);
while(!(queue.empty()))
{
int levelsize=queue.size();
Node* prev=NULL;
for(int i = 0 ; i < levelsize ; i++)
{
Node* current=queue.front();
queue.pop();
if(prev!=NULL)
prev->next=current;
prev=current;
if(current->left!=NULL)
queue.push(current->left);
if(current->right!=NULL)
queue.push(current->right);
}
}
return root;
}
};
Connect all level order siblings:
class Solution {
public:
Node* connect(Node* root)
{
return helper(root);
}
Node* helper(Node* root)
{
if(root==NULL)
return root;
queue<Node*>queue;
queue.push(root);
while(!(queue.empty()))
{
int levelsize=queue.size();
Node* prev=NULL;
Node* current=queue.front();
queue.pop();
if(prev!=NULL)
prev->next=current;
prev=current;
if(current->left!=NULL)
queue.push(current->left);
if(current->right!=NULL)
queue.push(current->right);
}
return root;
}
};

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.

Cannot insert and print out linked list

I'm trying to create a simple linked list class. The program runs but it gives me wrong output. And it seems like linked list doesn't insert the new nodes as I want.
class Node
{
public:
std::string name;
Node *next;
};
class ProductName
{
private:
Node *head;
public:
ProductName()
{
head = NULL;
}
void insertNode(std::string input)
{
Node *temp;
temp = new Node;
temp->name = input;
temp->next = head;
head = temp;
}
void printOut()
{
Node *p;
p = head;
while (p->next != NULL)
{
std::cout << p->name << " ";
p = p->next;
}
}
};
int main()
{
ProductName object;
object.insertNode("Hello");
object.insertNode("world!");
object.printOut();
}
I expect the output is Hello world!, but it prints out a string of random character 005C4BA0
Edit: I forgot the pointer... It's p->name not p in the print function. However, now my result is world!.
First issue: your are always inserting into the beginning by replacing the head. If you expect your nodes to appears in order of insertion you should insert them in the end:
class ProductName
{
private:
Node *head;
Node *tail; // additional member to track the last node
public:
ProductName()
: head(nullptr), tail(nullptr)
{ }
void insertNode(std::string input)
{
Node *temp = new Node{ std::move(input), nullptr };
if (tail) {
tail->next = temp;
tail = temp;
} else {
head = tail = temp;
}
}
}
Second issue: your are printing all the elements that have next which means that the last element won't be printed.
void printOut()
{
Node *p = head;
// print while p != nullptr
// this also properly handles the empty list when head == nullptr
while (p)
{
std::cout << p->name << " ";
p = p->next;
}
}

Error in code when searching through the right subtree in my binary search tree

In one of my classes at Uni we are creating Binary search trees and inserting data and looking them up. My code make sense in my head and because of this I cannot find the error anywhere. I have spent ages trying to find the error but cannot find it anywhere. The only thing that might be causing an error is that the precompiled headers didn't work when I started so i removed them from my project. The error only occurrs when i try to use the BST.Lookup and choose a key that is on the right subtree.
This is my main cpp file:
// BinarySearchTrees.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include "BST.h"
#include <iostream>
#include <fstream>
#include <string>
void ReadFile(BST &Bst)
{
int iKey;
std::string Key;
std::string Data;
std::ifstream testFile("Test.txt");
if (testFile.is_open())
{
while (!testFile.eof())
{
getline(testFile, Key, ' ');
getline(testFile, Data);
iKey = stoi(Key);
Bst.Insert(iKey, Data);
}
}
}
int main()
{
std::string Option;
int Choice;
BST BST;
//ReadFile(BST);
BST.Insert(6, "Oscar");
BST.Insert(20, "Ben");
BST.Insert(99, "James");
BST.Insert(1, "Alex");
while (Option != "exit")
{
std::cout << "If you wish to Lookup a Node, Insert value to find. Enter 'exit' to close" << std::endl;
getline(std::cin, Option);
if (Option == "exit")
break;
else
{
Choice = stoi(Option);
BST.Lookup(Choice);
}
}
return 0;
}
I believe that the readfile code may be incorrect but am unsure.
My Binary Search Tree Class:
#include "BST.h"
struct BST::Node {
Key key;
Item item;
Node* leftChild;
Node* rightChild;
Node(Key, Item);
};
void BST::Insert(Key inputKey, Item inputItem)
{
Node* previousNode = nullptr;
if (root == nullptr)
{
root = new Node(inputKey, inputItem);
}
else
{
InsertRec(inputKey, inputItem, root, previousNode);
}
}
void BST::InsertRec(Key inputKey, Item inputItem, Node* & Current, Node* & previousNode)
{
if (Current != nullptr)
{
previousNode = Current;
}
bool isLeft = false;
if (!isLeaf(Current))
{
if (inputKey > Current->key)
{
isLeft = false;
InsertRec(inputKey, inputItem, Current->rightChild, previousNode);
}
else if (inputKey < Current->key)
{
isLeft = true;
InsertRec(inputKey, inputItem, Current->leftChild, previousNode);
}
else
{
Current->item = inputItem;
}
}
else
{
Current = new Node(inputKey, inputItem);
if (isLeft)
{
previousNode->leftChild = Current;
}
else
{
previousNode->rightChild = Current;
}
}
}
BST::Item* BST::Lookup(Key soughtKey)
{
Item* Item = LookupRec(soughtKey, root);
std::string Display = /*std::to_string(soughtKey) + ": " + */ *Item;
std::cout << Display << std::endl;
return Item;
}
BST::Item* BST::LookupRec(Key soughtKey, Node* currentNode)
{
if (!isLeaf(currentNode))
{
if ((currentNode->key > soughtKey))
{
LookupRec(soughtKey, currentNode->leftChild);
}
else if ((currentNode->key < soughtKey))
{
LookupRec(soughtKey, currentNode->rightChild);
}
else
{
return &currentNode->item;
}
}
else
{
return nullptr;
}
}
bool BST::isLeaf(Node* n)
{
if (nullptr == n)
{
return true;
}
else
{
return false;
}
}
BST::BST()
{
}
BST::Node::Node(Key K, Item I)
{
key = K;
item = I;
leftChild = nullptr;
rightChild = nullptr;
}
And finally my header file for the binary search tree:
#pragma once
#include "iostream"
#include "string"
class BST
{
public:
using Key = int;
using Item = std::string;
void Insert(Key, Item);
Item* Lookup(Key);
BST();
private:
struct Node;
Node* root = nullptr;
static bool isLeaf(Node*);
static Item* LookupRec(Key, Node*);
static void InsertRec(Key, Item, Node* &, Node* &);
};
Any help would be greatly appreciated. I've been stuck on this for too long and I cannot progress without fixing this first.
The Test.txt file is filled with keys and items that are read and inputted like how I do it manually at the start of my main function, so I dont think the error is the file data.
Thanks in advance
UPDATE: Have finally found the error. The problem was with the bool isLeft in my InsertRec function. The bool was always false due to the recursion so have changed the code to compare previousNode->Key with Current->Key to determine if the child goes left or right

Resources