How to keep track of layers when traversing a binary tree? - c++

If I need to print out each elements of a binary tree constructed with the struct below. How could I keep track of which layer of elements I am printing?
struct for a binary tree node
For example:
any binary tree
Expected output:
layer 0: 12
layer -1: 28 19
layer -2: 94 32
layer -3: 65 18 72

Solution using queue based on GeeksForGeeks
#include <iostream>
#include <queue>
using namespace std;
// A Binary Tree Node
struct node
{
struct node *left;
int data;
struct node *right;
};
// Iterative method to do level order traversal
// line by line
void printLevelOrder(node *root)
{
// Base Case
if (root == NULL)
return;
// Create an empty queue for level order tarversal
queue<node *> q;
// Enqueue Root and initialize height
q.push(root);
int i = 0;
while (q.empty() == false)
{
cout << "layer " << i << ": ";
// nodeCount (queue size) indicates number
// of nodes at current lelvel.
int nodeCount = q.size();
// Dequeue all nodes of current level and
// Enqueue all nodes of next level
while (nodeCount > 0)
{
node *node = q.front();
cout << node->data << " ";
q.pop();
if (node->left != NULL)
q.push(node->left);
if (node->right != NULL)
q.push(node->right);
nodeCount--;
}
cout << endl;
--i;
}
}
// Utility function to create a new tree node
node *newNode(int data)
{
node *temp = new node;
temp->data = data;
temp->left = NULL;
temp->right = NULL;
return temp;
}
// Driver program to test above functions
int main()
{
// Create binary tree
node *root = newNode(12);
root->left = newNode(28);
root->right = newNode(19);
root->left->left = newNode(94);
root->left->left->left = newNode(65);
root->left->left->right = newNode(18);
root->right->left = newNode(32);
root->right->left->right = newNode(72);
printLevelOrder(root);
return 0;
}
Solution using recursive function and helper function based on CrazyForCode:
#include <iostream>
using namespace std;
struct node
{
int data;
struct node *left;
struct node *right;
};
void printLevel(node *, int);
int height(struct node *node);
/* Function to print level order traversal a tree*/
void printLevelOrder(struct node *root)
{
int h = height(root);
int i;
for (i = 1; i <= h; i++){
printf("layer %d: ",i*-1+1);
printLevel(root, i);
cout << endl;
}
}
/* Print nodes at a given level */
void printLevel(struct node *root, int level)
{
if (root == NULL)
return;
if (level == 1)
{
printf("%d ", root->data);
}
else if (level > 1)
{
printLevel(root->left, level - 1);
printLevel(root->right, level - 1);
}
}
/* Compute the "height" of a tree */
int height(struct node *node)
{
if (node == NULL)
return 0;
else
{
int lheight = height(node->left);
int rheight = height(node->right);
if (lheight > rheight)
return (lheight + 1);
else
return (rheight + 1);
}
}
node *newNode(int data)
{
node *temp = new node;
temp->data = data;
temp->left = NULL;
temp->right = NULL;
return temp;
}
int main()
{
// Create binary tree
node *root = newNode(12);
root->left = newNode(28);
root->right = newNode(19);
root->left->left = newNode(94);
root->left->left->left = newNode(65);
root->left->left->right = newNode(18);
root->right->left = newNode(32);
root->right->left->right = newNode(72);
printLevelOrder(root);
return 0;
}

Related

Height of Skewed Binary Search Tree

I have implemented the code as follows, In this I have made two functions to calculate the height of binary search tree using recursion and without recursion.
#include <iostream>
#include <list>
using namespace std;
struct node
{
int key;
struct node *left, *right;
};
struct node *newNode(int item)
{
struct node *temp = new node;
temp->key = item;
temp->left = temp->right = NULL;
return temp;
}
void inorder(struct node *root)
{
if (root != NULL)
{
inorder(root->left);
printf("%d ", root->key);
inorder(root->right);
}
}
struct node *insert(struct node *node, int key)
{
if (node == NULL)
return newNode(key);
if (key < node->key)
node->left = insert(node->left, key);
else if (key > node->key)
node->right = insert(node->right, key);
return node;
}
int heightRecursive(struct node *node)
{
if (node == NULL)
return -1;
else
{
int lDepth = heightRecursive(node->left);
int rDepth = heightRecursive(node->right);
if (lDepth > rDepth)
return (lDepth + 1);
else
return (rDepth + 1);
}
}
int heightNonRecursive(node* root)
{
if (root == NULL) {
return 0;
}
list<node*> queue;
queue.push_back(root);
node* front = NULL;
int height = 0;
while (!queue.empty())
{
int size = queue.size();
while (size--)
{
front = queue.front();
queue.pop_front();
if (front->left) {
queue.push_back(front->left);
}
if (front->right) {
queue.push_back(front->right);
}
}
height++;
}
return height;
}
int main()
{
struct node *root = NULL;
root = insert(root, 10);
insert(root, 20);
insert(root, 30);
insert(root, 40);
insert(root, 50);
insert(root, 60);
insert(root, 70);
insert(root, 75);
insert(root, 80);
inorder(root);
int h = heightRecursive(root);
cout << "\n\nHeight of tree using recursive function: " << heightRecursive(root);
cout << "\nHeight of tree using non-recursive function: " << heightNonRecursive(root);
return 0;
}
I have implemented a skewed binary tree like 10->20->30->40->50->60->70->75->80, but in the heightNonRecursive() function, I am getting the height of this binary search tree as 9. Please help where I am doing mistake.
Output of above code:
10 20 30 40 50 60 70 75 80
Height of tree using recursive function: 8
Height of tree using non-recursive function: 9
You have 9 different numbers in increasing order, in unbalanced tree, so the height should be 8, which is correct with recursive function.
10
20
30
40
50
60
70
75
80
With non-recursive function, you just have to start with height = -1;, it should return 0 if there is only one item in the tree.
int heightNonRecursive(node* root)
{
if (root == NULL)
return 0;
list<node*> queue;
queue.push_back(root);
node* front = NULL;
int height = -1; //<-start at -1
while (!queue.empty())
{
int size = queue.size();
while (size--)
{
front = queue.front();
queue.pop_front();
if (front->left)
queue.push_back(front->left);
if (front->right)
queue.push_back(front->right);
}
height++;
}
return height;
}

Merge sort a Linked list (segementation fault)

The below code is for merge sorting a linked list. Its giving out a segmentation fault. I really dont know how to deal with the above. All I could find was that I was trying to access a restricted part of the memory, the only place I think i could've gone wrong is re combining the two linked lists after splitting and sorting them under the split function body. I'd appreciate if I could get some guidance on how to deal with segmentation faults from here on & how to rectify them.
//Segmentation fault
#include <iostream>
using namespace std;
class Node
{
public:
int data;
Node *next;
Node(int data)
{
this->data = data;
next = NULL;
}
};
void print(Node *head)
{
Node *temp = head;
while (temp != NULL)
{
cout << temp->data << " ";
temp = temp->next;
}
}
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;
}
Node *sortedMerge(Node *h1, Node *h2)
{
// Node *fHead = NULL;
// Node *fTail = NULL;
if (!h1)
{
return h2;
}
if (!h2)
{
return h1;
}
if (h1->data < h2->data)
{
h1->next = sortedMerge(h1->next, h2);
return h1;
}
else
{
h2->next = sortedMerge(h1, h2->next);
return h2;
}
}
void split(Node *head, Node *h1, Node *h2)
{
Node *slow = head;
Node *fast = head->next;
while (fast != NULL)
{
fast = fast->next;
if (fast != NULL)
{
slow = slow->next;
fast = fast->next;
}
}
h1 = head;
h2 = slow->next;
slow->next = NULL;
}
void mergeSort_LL(Node *head)
{
Node *temp = head;
Node *h1;
Node *h2;
if ((temp == NULL) || (temp->next == NULL))
{
return;
}
split(temp, h1, h2);
mergeSort_LL(h1);
mergeSort_LL(h2);
head = sortedMerge(h1, h2);
}
int main()
{
Node *head = insert();
print(head);
cout << endl;
mergeSort_LL(head);
cout << "Sorted List is : " << endl;
print(head);
return 0;
}
Your call to split will not make h1 or h2 get a value. Arguments are passed by value. Since you evidently need h1 and h2 to get a different value from that split call, you should pass their addresses:
split(temp, &h1, &h2)
The function itself should therefore accept these addresses instead of the node pointers themselves:
void split(Node *head, Node **h1, Node **h2) {
// ...
*h1 = head;
*h2 = slow->next;
// ...
}

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.

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.

Converting a Binary Tree to Double Threaded Binary Tree?

I could not find anything on search to satisfy my question, if it exists, I'm sorry!
I am working on a college assignment about threaded binary trees. I.e. various kinds of traversals - inorder, postorder and preorder on double TBT.
This is the TBTNode struct:
struct TBTNode {
TBTNode *left, *right, *parent;
char data;
bool left_normal, right_normal;
TBTNode(char d) {
data = d;
left = NULL;
right = NULL;
parent = NULL;
left_normal = true;
right_normal = true;
}
};
As you can see, there is not much distinction between a Binary Tree node and a TBT node, except that the node's properties, viz. {left,right}_normal are set to true when required.
To create the tree, I have this:
class TBT {
TBTNode *root;
public:
TBT() {
root = new TBTNode(0);
root->right = root;
root->right_normal = true;
cout << "Root:" ;
root->left = create();
if(root->left)
root->left_normal = true;
}
TBTNode* create();
};
TBTNode* TBT::create() {
char data;
TBTNode *node = NULL;
cout << endl << "Enter data (0 to quit): ";
cin >> data;
if(data == '0')
return NULL;
node = new TBTNode(data);
cout << endl << "Enter left child of " << data;
node->left = create();
if(node->left)
node->left->parent = node;
else {
node->left = root;
node->right = node->parent;
node->left_normal = node->right_normal = false;
}
cout << endl << "Enter right child of " << data;
node->right = create();
if(node->right)
node->right->parent = node;
else {
node->left = node;
node->right = node->parent->parent;
node->left_normal = node->right_normal = false;
}
return node;
}
After the tree gets recursively created using the above code, I want to convert it into a double threaded binary tree. I know the concept that left child is linked to the child's inorder predecessor and right to inorder successor, but I am unable to create an algorithm. Can someone help me?
I found the solution myself. First traverse the tree in inorder and add nodes to an array as you go on. Then process the array to link threads, because for a given element x in the array, the one previous to x will be inorder predecessor and one after x will be inorder successor. For the first and last element, special checks are made to link them to the head node (not root).
Parent link isn't needed, and it's removed.
Code is as follows:
class TBT {
TBTNode *root;
void createInorderArray(TBTNode *T);
TBTNode **array;
unsigned array_size;
public:
TBT();
TBTNode* create();
void inorder();
void preorder();
};
TBT::TBT() {
root = new TBTNode(0);
root->right = root;
root->right_normal = true;
cout << "Root:" ;
root->left = create();
if(!root->left) {
root->left_normal = false;
root->left = root;
}
array = NULL;
array_size = 0;
createInorderArray(root->left);
for(unsigned i = 0; i < array_size; i++) {
if(!array[i]->left) {
array[i]->left = i == 0 ? root : array[i-1];
array[i]->left_normal = false;
}
if(!array[i]->right) {
array[i]->right_normal = false;
array[i]->right = i == (array_size - 1) ? root : array[i+1];
}
}
free(array);
array_size = 0;
}
void TBT::createInorderArray(TBTNode *T) {
if(!T)
return;
createInorderArray(T->left);
array = (TBTNode**) realloc(array, sizeof(TBTNode**) * ++array_size);
array[array_size-1] = T;
createInorderArray(T->right);
}