DS Unit3 Programs
DS Unit3 Programs
Given an array that represents a tree in such a way that array indexes are values
in tree nodes and array values give the parent node of that particular index (or
node). The value of the root node index would always be -1 as there is no parent
for root.
Ways to represent:
Trees can be represented in two ways as listed below:
•Dynamic Node Representation (Linked Representation).
•Array Representation (Sequential Representation).
Now, we are going to talk about the sequential representation of the trees.
In order to represent a tree using an array, the numbering of nodes can start
either from 0–(n-1) or 1– n, consider the below illustration as follows:
7.a. (i). Write a program that implement Binary tree(it ‘s operations) using arrays
int print_tree()
{
cout << "\n";
for (int i = 0; i < 10; i++)
{
if (tree[i] != '\0')
cout << tree[i];
else
cout << "-";
}
return 0;
}
// Driver Code
int main()
{
root('A');
set_left('B',0);
set_right('C', 0);
set_left('D', 1);
set_right('E', 1);
set_right('F', 2);
print_tree();
return 0;
}
OUTPUT:
ABCDE-F---
7.a. (ii). Write a program that implement Binary tree(it ‘s operations) using Linked
lists
//Represent the root of binary tree
#include <iostream>
struct node *root = NULL;
using namespace std;
#include <stdlib.h>
//createNode() will create a new node
#include <stdbool.h>
struct node* createNode(int data)
{
//Represent a node of binary tree
//Create a new node
struct node struct node *newNode = (struct node*)malloc(sizeof(struct node));
{
int data; //Assign data to newNode, set left and right child to NULL
struct node *left; newNode->data = data;
struct node *right; newNode->left = NULL;
}; newNode->right = NULL;
return newNode;
}
//Represent a queue
struct queue
{
int front, rear, size;
struct node* *arr;
};
//createQueue() will create a queue
struct queue* createQueue()
{
struct queue* newQueue = (struct queue*) malloc(sizeof( struct queue ));
newQueue->front = -1;
newQueue->rear = 0;
newQueue->size = 0;
newQueue->arr = (struct node**) malloc(100 * sizeof( struct node* ));
return newQueue;
}
//Adds a node to queue
void enqueue(struct queue* queue, struct node *temp)
{
queue->arr[queue->rear++] = temp;
queue->size++;
}
//Deletes a node from queue
struct node *dequeue(struct queue* queue)
{
queue->size--;
return queue->arr[++queue->front];
}
//insertNode() will add new node to the binary tree
void insertNode(int data)
{
//Create a new node
struct node *newNode = createNode(data);
//Check whether tree is empty
if(root == NULL)
{
root = newNode;
return;
}
else
{
//Queue will be used to keep track of nodes of tree level-wise
struct queue* queue = createQueue();
//Add root to the queue
enqueue(queue, root);
while(true)
{
struct node *node = dequeue(queue);
//If node has both left and right child, add both the child to queue
if(node->left != NULL && node->right != NULL)
{
enqueue(queue, node->left);
enqueue(queue, node->right);
}
else
{
//If node has no left child, make newNode as left child
if(node->left == NULL)
{
node->left = newNode;
enqueue(queue, node->left);
}
//If node has left child but no right child, make newNode as right child
else
{
node->right = newNode;
enqueue(queue, node->right);
}
break;
}
}
}
//inorder() will perform inorder traversal on binary search tree
void inorderTraversal(struct node *node)
{
//Check whether tree is empty
if(root == NULL)
{
cout<<"Tree is empty\n"<<endl;
return;
}
else
{
if(node->left != NULL)
inorderTraversal(node->left);
cout<< node->data<<endl;
if(node->right != NULL)
inorderTraversal(node->right);
}
}
int main()
{
//Add nodes to the binary tree
insertNode(1);
//1 will become root node of the tree
cout<<"Binary tree after insertion:"<<endl;
//Binary after inserting nodes
inorderTraversal(root);
insertNode(2);
insertNode(3);
//2 will become left child and 3 will become right child of root node 1
cout<<"Binary tree after insertion:"<<endl;
//Binary after inserting nodes
inorderTraversal(root);
insertNode(4);
insertNode(5);
//4 will become left child and 5 will become right child of node 2
cout<<"Binary tree after insertion:"<<endl;
//Binary after inserting nodes
inorderTraversal(root);
insertNode(6);
insertNode(7);
//6 will become left child and 7 will become right child of node 3
cout<<"Binary tree after insertion:"<<endl;
//Binary after inserting nodes
inorderTraversal(root);
return 0;
}
OUTPUT:
7.b.Write a C++ Program to Implement a Binary Tree traversal methods
/*
* C++ Program to Implement a Binary Tree traversal
*/
#include <iostream>
using namespace std;
struct tree
{
tree *l, *r;
int data;
} *root = NULL, *p = NULL, *np = NULL, *q;
void create()
{
int value,c = 0;
while (c < 7)
{
if (root == NULL)
{
root = new tree;
cout<<"enter value of root node\n";
cin>>root->data;
root->r=NULL;
root->l=NULL;
}
else
{ else if (value > p->data)
p = root; {
cout<<"enter value of node\n"; if (p->r == NULL)
cin>>value; {
while(true) p->r = new tree;
{ p = p->r;
if (value < p->data) p->data = value;
{ p->l = NULL;
if (p->l == NULL) p->r = NULL;
{ cout<<"value entered in right\n";
p->l = new tree; break;
p = p->l; }
p->data = value;
p->l = NULL; else if (p->r != NULL)
p->r = NULL; {
cout<<"value entered in left\n"; p = p->r;
break; }
} }
else if (p->l != NULL) }
{ }
p = p->l; c++;
} }
}
void inorder(tree *p) void postorder(tree *p)
{ {
if (p != NULL) if (p != NULL)
{ {
inorder(p->l); postorder(p->l);
cout<<p->data<<endl; postorder(p->r);
inorder(p->r); cout<<p->data<<endl;
} }
} }
void preorder(tree *p)
{ int main()
if (p != NULL) {
{ create();
cout<<p->data<<endl; cout<<"printing traversal in inorder\n";
preorder(p->l); inorder(root);
preorder(p->r); cout<<"printing traversal in preorder\n";
} preorder(root);
} cout<<"printing traversal in postorder\n";
postorder(root);
return 0;
}
OUTPUT:
Second Minimum Node In a Binary Tree in C++
Suppose there is a non-empty special binary tree with some non-negative value, here
each node in this tree has exactly two or zero children. If the node has two children,
then this node's value is the smaller value among its two children.
then the output will be 5. The smallest value is 2, the second smallest value is 5.
To solve this, we will follow these steps −
•Define a function TraverseNodes(), this will take node, min, nextMin,
•if node is null, then −
• return
•if val of node > min, then −
• if nextMin is same as -1 or val of node < nextMin, then −
• nextMin := val of node
•TraverseNodes(left of node, min, nextMin)
•TraverseNodes(right of node, min, nextMin)
OUTPUT: 5
7d.Write a program to print the height of a Binary tree.
#include <bits/stdc++.h>
using namespace std;
class node
{
public:
int data;
node *left, *right;
};
bool areTwoTreeSame(node * t1, node *t2)
{
if (t1 == NULL && t2 == NULL)
return true;
if (t1 == NULL || t2 == NULL)
return false;
return (t1->data == t2->data && areTwoTreeSame(t1->left, t2->left) &&areTwoTreeSame(t1->right, t2->right) );
}
bool isSubtree(node *tree, node *sub_tree)
{
if (sub_tree == NULL)
return true;
if (tree == NULL)
return false;
if (areTwoTreeSame(tree, sub_tree))
return true;
return isSubtree(tree->left, sub_tree) || isSubtree(tree->right, sub_tree);
}
#include<bits/stdc++.h>
using namespace std; NOTE: A Symmetric Tree Is A Tree
struct treenode Which Is A Mirror Image Of
{ Itself,whwere The Left And Right
int data; Nodes Of The Tree Are Same.
treenode * left;
treenode * right;
};
struct treenode * createNode(int d)
{
struct treenode * root = new treenode;
root -> data = d;
root -> left = NULL;
root -> right = NULL;
return root;
}
bool helper(struct treenode * root1, struct treenode * root2)
{
if (root1 == NULL and root2 == NULL)
return true;
if (root1 and root2 and root1 -> data == root2 -> data)
return (helper(root1 -> left, root2 -> right) and helper(root1 -> right, root2 -> left));
return false;
}
bool isSymmetry(struct treenode * root)
{
return helper(root, root);
}
Input/Output:
int main() False
{
struct treenode * root = NULL;
root = createNode(4);
root -> left = createNode(2);
root -> right = createNode(2);
root -> left -> right = createNode(7);
root -> left -> left = createNode(5);
root -> right -> left = createNode(5);
root -> right -> right = createNode(7);
if (isSymmetry(root))
{
cout<< "True" <<endl;
}
else
{
cout<< "False" <<endl;
}
return 0;
}
8.a.Write a program to check if a binary tree is BST or not.
#include <iostream>
#include <cstdlib>
#include <climits>
using namespace std;
struct n
{
int d;
n* l;
n* r;
};
int BSTUtil(n* node, int min, int max);
int isBST(n* node)
{
return(BSTUtil(node, INT_MIN, INT_MAX));
}
int BSTUtil(struct n* node, int min, int max)
{
if (node==NULL)
return 1;
if (node->d < min || node->d > max)
return 0;
return BSTUtil(node->l, min, node->d - 1) &&BSTUtil(node->r, node->d + 1, max);
}
n* newN(int d)
{
n* nod = new n;
nod->d = d;
nod->l = NULL;
nod->r = NULL;
return nod;
}
int main()
{ Input/Output
n *root = newN(7); For Tree-1:
root->l = newN(6); The Given Binary Tree is not a BST
root->r = newN(10); For Tree-2:
root->l->l = newN(2); The Given Binary Tree is a BST
root->l->r = newN(4);
if (isBST(root))
cout<<"The Given Binary Tree is a BST"<<endl;
else
cout<<"The Given Binary Tree is not a BST"<<endl;
n *root1 = newN(10);
root1->l = newN(6);
root1->r = newN(11);
root1->l->l = newN(2);
root1->l->r = newN(7);
if (isBST(root1))
cout<<"The Given Binary Tree is a BST"<<endl;
else
cout<<"The Given Binary Tree is not a BST"<<endl;
return 0;
}
8.b. Write a program to perform the following operations on BST:
i) Insertion ii) Deletion iii) Search
// C++ program to demonstrate insertion in a BST recursively.
#include <iostream>
using namespace std;
class BST
{
int data;
BST *left, *right;
public:
BST(); // Parameterized constructor
BST(int); // Insert function.
BST* Insert(BST*, int); // Inorder traversal.
void Inorder(BST*);
BST * Search(BST * ,int )
};
// Default Constructor definition.
BST ::BST(): data(0), left(NULL) , right(NULL)
{
}
// Parameterized Constructor definition.
BST ::BST(int value)
{
data = value;
left = right = NULL;
}
// Insert function definition.
BST* BST ::Insert(BST* root, int value)
{
if (!root)
{
// Insert the first node, if root is NULL.
return new BST(value);
}
// Search a key in BST
BST* BST ::Search(BST * root,
// Insert data int value)
if (value > root->data)
{ {
if (root==NULL|| root->data == value)
root->right = Insert(root->right, value);
{
} return root;
else }
{ // Insert data.
root->left = Insert(root->left, value); if (root->data<value)
} return search(root->right, value);
// Return 'root' node, after insertion. return search(root->left, value);
return root; }
}
// Inorder traversal function.This gives data in sorted order.
BST* BST ::Delete(BST* root, value)
{
if (root == NULL)
return root;
// If the key to be deleted is smaller than the root's key, then it lies in left subtree
if (value< root->data)
root->left = Delete(root->left, value);
// If the key to be deleted is greater than the root's key, then it lies in right subtree
else if (value> root->data)
root->right = Delete(root->right, value);
// if key is same as root's key, then This is the node to be deleted
else
{
// node has no child
if (root->left==NULL && root->right==NULL)
return NULL;
// node with only one child or no child
else if (root->left == NULL)
{
BST* temp = root->right;
free(root);
return temp;
}
else if (root->right == NULL)
{
BST* temp = root->left;
free(root);
return temp;
}
// node with two children: Get the inorder successor
// (smallest in the right subtree)
// Copy the inorder successor's content to this node
root->data = temp->data;
// Delete the inorder successor
root->right = Delete(root->right, temp->data);
}
return root;
}
void BST ::Inorder(BST* root)
{
if (!root)
{
return;
}
Inorder(root->left);
cout<< root->data <<endl;
Inorder(root->right);
}
// Driver code
int main()
{ Input/Output:
BST b, *root = NULL; 20304050607080
root = b.Insert(root, 50); Search Key found: false
b.Insert(root, 30); //Delete key 60
b.Insert(root, 20); 20 30 40 50 70 80
b.Insert(root, 40);
b.Insert(root, 70);
b.Insert(root, 60);
b.Insert(root, 80);
b.Inorder(root);
BST ans*=b.Search(root,10);
cout<<”Search key is found : ”;
if(ans->value == 10)
cout<<”true”;
else
cout<<”false”;
return 0;
}
8.c. Write a program to print the Minimum and maximum element.
// C program to print minimum and maximum element in binary search tree
#include<stdio.h>
#include<stdlib.h>
struct node
{
int key;
struct node *left, *right;
};