To print the entire sub tree of a given tree recursively - c++

I know how to print the left and right view of a binary tree, but I want to print the entire left subtree of a given tree recursively. So, below is the code I use, and though I am getting the desired output, I feel this is not the proper approach. Is there any other way to achieve the same result without setting the root node's right child to nullptr?
#include<iostream>
using namespace std;
class node
{
public:
int data;
node *lchild;
node *rchild;
};
node *CreateNode(int data)
{
node *NewNode = new node();
NewNode->data = data;
NewNode->lchild = nullptr;
NewNode->rchild = nullptr;
return NewNode;
}
void printEntireTree(node *root)
{
if (root == nullptr)
return;
else
{
cout << root->data<<endl;
printEntireTree(root->lchild);
printEntireTree(root->rchild);
}
}
int main()
{
node *root = CreateNode(3);
root->lchild = CreateNode(1);
root->rchild = CreateNode(4);
root->lchild->rchild = CreateNode(2);
root->lchild->lchild = CreateNode(7);
root->lchild->lchild->lchild = CreateNode(8);
root->lchild->lchild->rchild = CreateNode(9);
root->rchild->lchild = CreateNode(5);
cout << "to print entire left sub tree" << endl;
node *temp = root->rchild;
root->rchild = nullptr;
printEntireTree(root);
root->rchild = temp;
temp = root->lchild;
cout << "entire right sub tree is" << endl;
root->lchild = nullptr;
printEntireTree(root);
root->lchild = temp;
}

#include<iostream>
using namespace std;
class node
{
public:
int data;
node *lchild;
node *rchild;
};
node *CreateNode(int data)
{
node *NewNode = new node();
NewNode->data = data;
NewNode->lchild = nullptr;
NewNode->rchild = nullptr;
return NewNode;
}
void printEntireTree(node *root, node *ro2)
{
if(root== ro2->lchild || root== ro2->rchild)
{
cout << ro2->data<<endl;
}
if (root == nullptr)
return;
else
{
cout << root->data<<endl;
printEntireTree(root->lchild, ro2);
printEntireTree(root->rchild, ro2);
}
}
int main()
{
node *root = CreateNode(3);
root->lchild = CreateNode(1);
root->rchild = CreateNode(4);
root->lchild->rchild = CreateNode(2);
root->lchild->lchild = CreateNode(7);
root->lchild->lchild->lchild = CreateNode(8);
root->lchild->lchild->rchild = CreateNode(9);
root->rchild->lchild = CreateNode(5);
cout << "to print entire left sub tree" << endl;
printEntireTree(root->lchild, root);
cout << "entire right sub tree is" << endl;
printEntireTree(root->rchild, root);
}

Related

How Can I Create A Single function that can create multiple Linked Lists

as shown in the code , i have to use 2 similar functions for creating 2 linked lists . isn't there a way i can create as many lists as i want with just one function , i tried using struct Node **p and struct Node *p as a parameter to the function but the didn't work
can someone help me to create multiple linked lists using this same function
and i want to create a append function not a insert function which asks for position as well.
#include <iostream>
using namespace std;
struct Node
{
int data = 10 ;
struct Node *next;
} *first , *second , *third;
void Display(struct Node *p)
{
while (p)
{
cout<<p->data<<" ";
p = p->next ;
}
cout<<"\n";
}
void Append_1(int elem)
{
Node* t , *last;
t = new Node;
t->data = elem;
t->next = NULL;
if(first == 0)
first = last = t;
else
{
last->next = t;
last = t;
}
}
void Append_2(int elem)
{
Node* t , *last;
t = new Node;
t->data = elem;
t->next = NULL;
if(second == 0)
second = last = t;
else
{
last->next = t;
last = t;
}
}
//void SortMerge(struct Node *p , struct Node *q);
int main()
{
Append_1(3);
Append_1(7);
Display(first);
Append_2(10);
Append_2(14);
Append_2(21);
Display(second);
//SortMerge(first , second);
Display(third);
return 0;
}
You can create a class like here:
struct Node{
int data;
Node* next;
Node* previous;
};
class Graph{
public:
Graph(int = 0);
~Graph();
void display_left_right();
void display_right_left();
void append(int);
void append_at_pos(int,int);
void prepend(int);
int get_num_elt();
int get_data_at_pos(int);
private:
Node* head;
Node* tail;
int num_elt=0;
};
Graph::Graph(int first_data){
head = new Node;
head->next = NULL;
head->previous = NULL;
head->data = first_data;
tail = head;
num_elt++;
}
Graph::~Graph(){
Node* main_traverser = head;
while(main_traverser){
main_traverser = head->next;
delete head;
head = main_traverser;
}
std::cout <<"Graph deleted!" << std::endl;
}
void Graph::display_left_right(){
Node* traverser = head;
while(traverser != NULL){
std::cout << traverser->data << " ";
traverser = traverser->next;
}
std::cout << std::endl;
}
void Graph::display_right_left(){
Node* traverser = tail;
while(traverser != NULL){
std::cout << traverser->data << " ";
traverser = traverser->previous;
}
std::cout << std::endl;
}
void Graph::append(int new_data){
Node* add = new Node;
add->data = new_data;
add->next = NULL;
add->previous = tail;
tail->next = add;
tail = add;
num_elt++;
}
void Graph::append_at_pos(int pos, int new_data){
if(pos > num_elt+1 || pos<=0){std::cout << "Wrong position!" << std::endl; return;}
if(pos==1){
prepend(new_data);
return;
}
if(pos==num_elt+1){
append(new_data);
return;
}
Node* add = new Node;
Node* traverser = head;
add->data = new_data;
for(int i=0; i<pos-2; i++){
traverser = traverser->next;
}
add->next = traverser->next;
add->previous = traverser;
traverser->next->previous = add;
traverser->next = add;
}
void Graph::prepend(int new_data){
Node* add = new Node;
add->next = head;
add->previous = NULL;
add->data = new_data;
head->previous = add;
head = add;
num_elt++;
}
int Graph::get_num_elt(){
return num_elt;
}
int Graph::get_data_at_pos(int pos){
Node* traverser = head;
if(pos <=0 || pos> num_elt){std::cout << "Wrong position!" << std::endl; return 0;}
for(int i=0; i<pos-1; i++){
traverser = traverser->next;
}
return traverser->data;
}
main(){
Graph a(2);
a.append(3);
a.append(4);
a.prepend(1);
a.display_left_right();
a.append_at_pos(1,6);
a.display_left_right();
std::cout << "data at 1: " << a.get_data_at_pos(1) << std::endl;
}
When you say "create multiple linked lists," I think you mean creating nodes to a linked list, which you have 2 append functions. I think the reason you have these 2 functions is because you do not know where to start traversing your linked list. For this reason, I think in your main function you should declare the head of the linked list, a single node that is the start. Set it's data and next to null, and then pass the head value into a function so it can start traversing from the head. Here is a generic append function that adds a node on the end, where the parameters are a reference to the head node, and the value for the new node:
void append(Node ** head, int new_data)
{
Node * select_node = * head;
// select node is set to the head node, and will traverse until it is at the end
while (select_node -> next != NULL)
{
// select node is set to the next node until it is NULL (end of linked list)
select_node = select_node -> next;
}
// now that select node is the last node, we need to make it's next value a node
// and that node should be a new node (allocated in heap) with the value of the input value
//and the next value be NULL (because it's the end of the linked list)
Node * next_node = new Node();
next_node -> data = new_data;
next_node -> next = NULL;
select_node -> next = next_node;
}

Error in pointer allocation for a binary search tree

I am trying to create a binary tree using C++ classes and pointers. The tree is being initialized properly. However, when I add nodes to the tree, instead of adding them to the left or right sub-tree, the root node gets overwritten. I tried printing the inorder value to check if the nodes are added correctly or not, but that also prints nothing.
Here is the code for the same.
#include <iostream>
#include <conio.h>
#include <stdlib.h>
#include <cstdio>
using namespace std;
class Node{
private:
Node *left;
Node *right;
public:
int number;
Node(int number){
this->number = number;
this->left = NULL;
this->right = NULL;
}
void set_left_node(Node *node){
this->left = node;
}
void set_right_node(Node *node){
this->right = node;
}
Node* read_left_node(){
return this->left;
}
Node* read_right_node(){
return this->right;
}
};
class Binary_Tree{
public:
Node *root;
Binary_Tree(){
this->root = NULL;
}
Node* read_root(){
return this->root;
}
Node* insert_node(Node *root, Node node){
if(!root){
root = &node;
cout << "Inserted " << node.number << " " << root << endl;
return root;
}
else{
cout << "Root and node values " << root->number << " " << node.number << endl;
if(root->number < node.number){
root->set_right_node(insert_node(root->read_right_node(), node));
}
else{
root->set_left_node(insert_node(root->read_left_node(), node));
}
}
return root;
}
void inorder(Node *root){
if (root != NULL){
inorder(root->read_left_node());
cout<<root->number<<" ";
inorder(root->read_right_node());
}
}
};
int main(){
Binary_Tree bt = Binary_Tree();
bt.root = bt.insert_node(bt.root, Node(34));
bt.root = bt.insert_node(bt.root, Node(17));
bt.root = bt.insert_node(bt.root, Node(56));
cout << "Inorder" << endl;
bt.inorder(bt.root);
return 0;
}
Output:

Reversing a linked list using recursion

I don't know where I'm going wrong. Output shows 1 upon inputting 1 2 3 -1 (-1 to terminate insertion of nodes). Help is appreciated!
I can't seem to find the error in my code that is resulting in wrong output upon different test cases.
Other approaches to the same problem are also welcome.
Any tips so that i won't commit such errors in the future, along with some fundamentals(generally tips) of linked lists
#include <iostream>
using namespace std;
class Node
{
public:
int data;
Node *next;
Node(int data)
{
this->data = data;
next = NULL;
}
};
Node *insert()
{
int data;
cin >> data;
Node *head = NULL;
Node *tail = NULL;
while (data != -1)
{
Node *n = new Node(data);
if (head == NULL)
{
head = n;
tail = n;
}
else
{
tail->next = n;
tail = tail->next;
}
cin >> data;
}
return head;
}
void print(Node *head)
{
Node *temp = head;
while (temp != NULL)
{
cout << temp->data << " ";
temp = temp->next;
}
}
Node *rev_LL(Node *head)
{
if (head == NULL || head->next == NULL)
{
return head;
}
Node *smallAns = rev_LL(head->next);
Node *temp = smallAns;
while (temp->next != NULL)
{
temp = temp->next;
}
temp->next = head;
head->next = NULL;
return smallAns;
}
int main()
{
Node *head = insert();
print(head);
cout << endl;
cout << "After reversing the Linked list : " << endl;
rev_LL(head);
print(head);
cout << endl;
return 0;
}
You have to assign the return value of rev_LL to head instead of just ignoring that.
int main()
{
Node *head = insert();
print(head);
cout << endl;
cout << "After reversing the Linked list : " << endl;
//rev_LL(head);
head = rev_LL(head); // assign the result
print(head);
cout << endl;
return 0;
}

Segmentation Fault (core dumped) when trying to run Queue program - C++

I keep getting a Segmentation fault (core dumped) error every time I try to run my code with g++ on Linux. It compiles fine, but then that happens ... All the functions (remove, add and print) seem to have the same problem, I can't seem to figure out what's wrong... Please heeeelppp.
#include <iostream>
#include <string>
using namespace std;
//Create a node struct
struct Node {
int data;
Node *next;
Node *prev;
};
class Queue {
private:
Node *head;
Node *tail;
int size;
public:
Queue();
~Queue();
void add(int d);
int remove();
bool isEmpty();
void printQueue(bool o);
};
//set to NULL
Queue::Queue() {
head = tail = NULL;
size = 0;
}
//destructor
//call remove until empty
Queue::~Queue() {
while (!isEmpty())
remove();
}
//adds a node with the given data at the back of the queue
void Queue::add(int d) {
Node *temp = new Node();
temp->data = d;
temp->next = NULL;
if (isEmpty()) {
//add to head
head = temp;
} else {
//append
tail->next = temp;
tail = temp;
cout << "Added: " << tail->data << endl;
}
size++;
}
//removes the node at the head of the queue and returns its data
int Queue::remove() {
if (isEmpty()) {
cout << "The queue is empty." << endl;
} else {
Node *temp = new Node;
temp = head;
int value = head->data;
//moves pointer to next node
head = head->next;
cout << "Removed: " << head->data << endl;
size--;
delete temp;
return value;
}
}
//determines if the queue is empty
bool Queue::isEmpty() {
return (size == 0);
}
//prints the contents of the queue from front to back, or front
//to back, depending on the value of the parameter
void Queue::printQueue(bool o) {
if (isEmpty()) {
cout << "The queue is empty." << endl;
} else {
Node *p = new Node;
if (o == true) {
cout << "Printing in front to back:" << endl;
//print front to back
while(p != NULL) {
p = head;
cout << p->data << " ";
p = p->next;
}
} else if (o == false) {
cout << "Printing in back to front:" << endl;
//print back to front
while (p != NULL) {
p = tail;
cout << p->data << " ";
p = p->prev;
}
}
}
}
int main() {
Queue q;
q.add(8);
return 0;
}
EDIT: I've made some changes to the code... But I'm still getting the same error. I assume I'm not updating the head and the tail and/or the next and prev nodes correctly... I don't know why it's wrong or what I'm missing, though.
#include <iostream>
#include <string>
using namespace std;
struct Node {
int data;
Node *next;
Node *prev;
};
class Queue {
private:
Node *head;
Node *tail;
int size;
public:
Queue();
~Queue();
void add(int d);
int remove();
bool isEmpty();
void printQueue(bool o);
};
Queue::Queue() {
head = tail = NULL;
size = 0;
}
Queue::~Queue() {
while (!isEmpty())
remove();
}
void Queue::add(int d) {
Node *temp = new Node;
temp->data = d;
temp->next = NULL;
temp->prev = tail;
if (isEmpty()) {
//add to head
head = temp;
} else {
//append
tail->next = temp;
tail = temp;
cout << "Added: " << tail->data << endl;
}
size++;
}
int Queue::remove() {
if (isEmpty()) {
cout << "The queue is empty." << endl;
return 0;
} else {
Node *temp = head;
int value = head->data;
cout << "Removed: " << head->data << endl;
//moves pointer to next node
head = head->next;
head->prev = NULL;
size--;
delete temp;
return value;
}
}
bool Queue::isEmpty() {
return (size == 0);
}
void Queue::printQueue(bool o) {
if (isEmpty()) {
cout << "The queue is empty." << endl;
} else {
Node *p;
if (o == true) {
p = head;
cout << "Printing in front to back:" << endl;
//print front to back
while(p != NULL) {
cout << p->data << " ";
p = p->next;
}
} else if (o == false) {
p = tail;
cout << "Printing in back to front:" << endl;
//print back to front
while (p != NULL) {
cout << p->data << " ";
p = p->prev;
}
}
}
}
int main() {
Queue q;
q.add(9);
q.add(10);
q.add(11);
q.add(12);
q.add(13);
q.add(14);
q.add(15);
q.add(16);
q.remove();
q.remove();
q.printQueue(true);
q.printQueue(false);
return 0;
}
Lots of problems:
You have a double-linked Node but never update its prev member in the add/remove methods.
You are keeping track of both the Queue head/tail but don't properly update them when you add/remove nodes.
Both your forward and reverse loops in printQueue() are wrong and result in an infinite loop for any queue with 2 or more elements. Queue output should be just something like:
Node *p = head;
while (p != NULL)
{
cout << p->data << " ";
p = p->next;
}
Possible null pointer deference in remove() at cout << "Removed: " << head->data << endl; since you've already moved the head pointer by this time. Move the head after the cout.
Memory leak in Queue::remove() at Node *temp = new Node;. Just do Node* temp = head;.
Memory leak in Queue::printQueue() at Node *p = new Node;. You don't need to allocate a node here.
No return value in remove() for an empty queue.
Edit
Don't forget to initialize the tail when adding a node to an empty list:
if (isEmpty()) {
head = temp;
tail = temp;
}
To remove a node from the head of a non-empty list it should be something like:
Node *temp = head;
head = head->next;
if (head) head->prev = NULL;
size--;
delete temp;
if (isEmpty()) tail = NULL;

Insert values in Binary Search Trees

I was trying to write a method which set values in a binary search tree. I have implemented a simple technique of recursion to add nodes in the tree. But when I input the values and ran the code I got segmentation fault:
struct Node
{
int data;
Node* leftN;
Node* rightN;
};
typedef Node* Node_ptr;
Node_ptr head;
//INSERT_VALUE FUNCTION
Node* new_node(int key)
{
Node* leaf = new Node;
leaf->data = key;
leaf->leftN = NULL;
leaf->rightN = NULL;
}
Node* insert_value(Node_ptr leaf, int key)
{
if(leaf == NULL)
return(new_node(key));
else
{
if(key <= leaf->data)
leaf->leftN = insert_value(leaf->leftN, key);
else
leaf->rightN = insert_value(leaf->rightN, key);
return(leaf);
}
}
//PRINT FUNCTION
void printTree(Node_ptr leaf)
{
if(leaf == NULL)
return;
printTree(leaf->leftN);
cout << "Data element: " << leaf->data << endl;
printTree(leaf->rightN);
}
//MAIN
int main()
{
Node_ptr root = NULL;
Node_ptr tail;
int i;
int x;
//initialize values
for(i = 0; i < 20; i++)
{
x = rand() % 1000 + 1;
tail = insert_value(root, x);
root = head;
}
root = head;
printTree(root);
root = head;
cout << "Head Node: " << root->data << endl;
return 0;
}
You are getting a segmentation fault because you never set the head, there for when you get to the line
cout << "Head Node: " << root->data << endl;
Your root value will be NULL, (since it was set to by head, which is NULL).
A "root" (or "head") node is typically a special case scenario, you should check to see if that node has been constructed at the top of insert_value, and if not, then you assign the node node to it.
Also, your code has in error in it as new_node does not return a value.