Document 3 Final

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 11

INTRODUCTION TO TREES, GRAPHS, MAPS AND SETS

I. Tree
 Definition: A tree is a nonlinear hierarchical data structure that consists of
nodes connected by edges.
 Terminologies:
o Node: an entity that contains a key or value and pointers to its
child nodes.The last nodes of each path are called leaf nodes or
external nodes that do not contain a link/pointer to child nodes.
The node having at least a child node is called an internal node.
o Edge: the link between any two nodes
o Root: the topmost node of a tree
o Height of a node: number of edges from the node to the
deepest leaf
o Depth of a Node: The depth of a node is the number of edges
from the root to the node.
o Height of a Tree: height of the root node or the depth of the
deepest node.
o Degree of a Node: total number of branches of that node.
o Forest: collection of disjoint trees is called a forest.
 Types:
o BINARY TREE: a tree data structure in which each parent
node can have at most two children. Each node of a binary tree
consists of three items: data item, address of left child, address
of right child.
o BINARY SEARCH TREE: A binary search tree is
distinguished from a regular binary tree by three key properties.
Firstly, in a binary search tree, all nodes in the left subtree are
strictly smaller than the root node. Secondly, all nodes in the
right subtree are strictly greater than the root node. Lastly, these
properties apply recursively to both the left and right subtrees
of every node, ensuring that each subtree is itself a valid binary
search tree.

o AVL TREE: a self-balancing binary search tree in which each


node maintains extra information called a balance factor
(Balance Factor = (Height of Left Subtree - Height of Right
Subtree) or (Height of Right Subtree - Height of Left Subtree)
whose value is either -1, 0 or +1.

o B-TREE: B-tree is a special type of self-balancing search tree


in which each node can contain more than one key and can
have more than two children. It is a generalized form of the
binary search tree.

 Code:
Code Output
#include <iostream>
using namespace std;

struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;

TreeNode(int value) : val(value),


left(NULL), right(NULL) {}
};

TreeNode* createNode(int value) {


TreeNode* newNode = new
TreeNode(value);
return newNode;
}

TreeNode* insert(TreeNode* root,


int value) {
if (root == NULL) {
return createNode(value);
}

if (value < root->val) {


root->left = insert(root->left,
value);
} else if (value > root->val) {
root->right = insert(root-
>right, value);
}

return root;
}

void inorderTraversal(TreeNode*
root) {
if (root != NULL) {
inorderTraversal(root->left);
cout << root->val << " ";
inorderTraversal(root->right);
}
}

int main() {
TreeNode* root = NULL;

root = insert(root, 10);


insert(root, 5);
insert(root, 15);
insert(root, 3);
insert(root, 7);
insert(root, 20);

cout << "In-order Traversal: ";


inorderTraversal(root);

return 0;
}

II. Graphs
 Definition: a collection of nodes that have data and are connected to other
nodes.
 Terminologies:
o Adjacency: A vertex is said to be adjacent to another vertex if
there is an edge connecting them. Vertices 2 and 3 are not
adjacent because there is no edge between them.
o Path: A sequence of edges that allows you to go from vertex A
to vertex B is called a path. 0-1, 1-2 and 0-2 are paths from
vertex 0 to vertex 2.
o Directed Graph: A graph in which an edge (u,v) doesn't
necessarily mean that there is an edge (v, u) as well. The edges
in such a graph are represented by arrows to show the direction
of the edge.
 Graph is represented in two ways:

 Code:
Code Output
#include <iostream>
#include <vector>
using namespace std;

class Graph {
public:
Graph(int vertices);
void addEdge(int v, int w);
void printGraph();

private:
int vertices;
vector<vector<int> >
adjacencyList;
};

Graph::Graph(int vertices) {
this->vertices = vertices;
adjacencyList.resize(vertices);
}

void Graph::addEdge(int v, int w) {


adjacencyList[v].push_back(w);
adjacencyList[w].push_back(v);
}

void Graph::printGraph() {
for (int i = 0; i < vertices; ++i) {
cout << "Vertex " << i << ": ";
for (vector<int>::iterator it =
adjacencyList[i].begin(); it !=
adjacencyList[i].end(); ++it) {
cout << *it << " ";
}
cout << endl;
}
}

int main() {
int vertices, edges;
cout << "Enter the number of
vertices: ";
cin >> vertices;

Graph graph(vertices);

cout << "Enter the number of


edges: ";
cin >> edges;

cout << "Enter the edges (vertex


pairs):" << endl;
for (int i = 0; i < edges; ++i) {
int v, w;
cout << "Enter edge " << (i + 1)
<< " (vertex pair): ";
cin >> v >> w;
graph.addEdge(v, w);
}

cout << "Graph representation


using adjacency list:" << endl;
graph.printGraph();
return 0;
}

III. Maps
 Definition: Map data structure (also known as a dictionary, associative array,
or hash map) is defined as a data structure that stores a collection of key-value
pairs, where each key is associated with a single value.

 Types:
o Hash Map: a data structure that uses a hash function to map
keys to indices in an array.
o Tree Map: a data structure that uses a hash function to map
keys to indices in an array.
o Linked Hash Map: a type of map that maintains a doubly-
linked list of the entries in the map, in the order in which they
were inserted.
o Trie Map: type of map that is used to store a set of strings,
where each node in the tree represents a prefix of one or more
strings.
o Bloom Filter Map: a type of map that uses a bloom filter, a
probabilistic data structure, to determine whether a key is
present in the map or not.
 Code:
Code Output
#include <iostream>
#include <map>
using namespace std;

void demonstrateMap() {
map<int, string> myMap;

myMap[1] = "One";
myMap[2] = "Two";
myMap[3] = "Three";
myMap[4] = "Four";
myMap[5] = "Five";

cout << "Map elements:" <<


endl;

for (map<int, string>::iterator it =


myMap.begin(); it != myMap.end();
++it) {
cout << "Key: " << it->first <<
", Value: " << it->second << endl;
}
}

int main() {
demonstrateMap();
return 0;
}

IV. Sets
 Definition: Sets is a data structure that stores unique elements of the same type
in a sorted order. Each value is a key, which means that we access each value
using the value itself.

 Code:
Code Output
#include <iostream>
#include <set>
using namespace std;

void demonstrateSet() {
set<int> mySet;

mySet.insert(5);
mySet.insert(2);
mySet.insert(8);
mySet.insert(1);
mySet.insert(10);

cout << "Set elements:" << endl;

for (set<int>::iterator it =
mySet.begin(); it != mySet.end(); +
+it) {
cout << *it << endl;
}
}

int main() {
demonstrateSet();
return 0;
}

BNT Insertion of Node


o Binary tree insertion involves adding a new node to a binary tree by comparing its
value to the current node's value. If the new value is less, it goes to the left; if greater,
it goes to the right. This process continues recursively until an empty spot is found,
where the new node is inserted. This ensures that the tree's order is maintained: nodes
on the left are smaller, and nodes on the right are larger.
o Code:
Code Output
#include <iostream>
using namespace std;

class TreeNode {
public:
int data;
TreeNode* left;
TreeNode* right;

TreeNode(int value) :
data(value), left(NULL),
right(NULL) {}
};

TreeNode* createNode(int
data) {
return new TreeNode(data);
}

void insertLeft(TreeNode*
parent, int data) {
if (parent) {
parent->left =
createNode(data);
cout << "Inserted: " <<
data << " as the left child of "
<< parent->data << endl;
}
}

void insertRight(TreeNode*
parent, int data) {
if (parent) {
parent->right =
createNode(data);
cout << "Inserted: " <<
data << " as the right child of "
<< parent->data << endl;
}
}

int main() {
TreeNode* root =
createNode(7);
cout << "Inserted: " << root-
>data << " as the root" << endl;

insertLeft(root, 2);
insertRight(root, 3);
insertLeft(root->left, 4);
insertRight(root->left, 5);

return 0;
}

BNT Deletion of Node


o Deleting a node from a binary tree involves finding the target node and handling three
scenarios. If the node has no children, it's removed directly. If it has one child, that
child takes its place. If it has two children, it's replaced by its in-order successor (the
smallest node in its right subtree), and then the successor is deleted. This process
ensures the tree's structure and ordering are maintained throughout the deletion.
o Code:
Code Output
#include <iostream>
using namespace std;

struct TreeNode {
int data;
TreeNode* left;
TreeNode* right;

TreeNode(int val) :
data(val), left(NULL),
right(NULL) {}
};

TreeNode*
insertNode(TreeNode* root,
int key) {
if (root == NULL) {
return new
TreeNode(key);
}

if (key < root->data) {


root->left =
insertNode(root->left, key);
} else {
root->right =
insertNode(root->right, key);
}

return root;
}

TreeNode*
findMin(TreeNode* node) {
while (node->left != NULL)
{
node = node->left;
}
return node;
}

TreeNode*
deleteNode(TreeNode* root,
int key) {
if (root == NULL) {
return root;
}

if (key < root->data) {


root->left =
deleteNode(root->left, key);
} else if (key > root->data) {
root->right =
deleteNode(root->right, key);
} else {
if (root->left == NULL) {
TreeNode* temp =
root->right;
delete root;
return temp;
} else if (root->right ==
NULL) {
TreeNode* temp =
root->left;
delete root;
return temp;
}

TreeNode* temp =
findMin(root->right);
root->data = temp->data;
root->right =
deleteNode(root->right, temp-
>data);
}

return root;
}

int main() {
TreeNode* root = NULL;

root = insertNode(root, 5);


root = insertNode(root, 3);
root = insertNode(root, 7);
root = insertNode(root, 2);
root = insertNode(root, 4);

root = deleteNode(root, 3);

return 0;
}

BNT in order Traversal


o Binary tree in-order traversal is a method of visiting and processing nodes in a binary
tree by following a specific sequence. The traversal starts at the root node and
recursively moves to the left subtree. For each node encountered, it processes the
node's value. After processing the left subtree, it moves back to the current node,
processes its value, and then proceeds to the right subtree. This process continues
until all nodes in the binary tree have been visited. In simple terms, in-order traversal
outputs the values of nodes in ascending order for a binary search tree, as it first
explores the left subtree, then the current node, and finally the right subtree. It is a
fundamental approach to examining and working with the contents of a binary tree.
o Code:
Code Output
#include <iostream>
using namespace std;

class TreeNode {
public:
int data;
TreeNode* left;
TreeNode* right;

TreeNode(int value) :
data(value), left(NULL),
right(NULL) {}
};

void inorderTraversal(TreeNode*
root) {
if (root) {
inorderTraversal(root->left);
cout << root->data << " ";
inorderTraversal(root-
>right);
}
}

int main() {
TreeNode* root = new
TreeNode(4);
root->left = new TreeNode(2);
root->right = new TreeNode(6);
root->left->left = new
TreeNode(1);
root->left->right = new
TreeNode(3);
root->right->left = new
TreeNode(5);
root->right->right = new
TreeNode(7);

cout << "In-order Traversal of


BST:" << endl;
inorderTraversal(root);
cout << endl;

return 0;
}

References:
Tree Data Structure (programiz.com)
What is Graph in Data Structure & Types of Graph? (simplilearn.com)
Graph Data Structure (programiz.com)
Introduction to Map – Data Structure and Algorithm Tutorials - GeeksforGeeks
Sets in C++ Explained with Examples | Udacity

You might also like