0% found this document useful (0 votes)
37 views19 pages

Lab Manual 13 DSA

The document provides information about trees as a data structure. It defines trees and describes their key components like nodes, edges, root, leaves, internal nodes, etc. It then focuses on binary trees, defining them as trees where each node has at most two children. It describes different types of binary trees including strictly binary trees, where each node has two children or none; complete binary trees, where all levels are fully filled except the lowest; and extended binary trees, which are made full by adding dummy nodes. The objective of the lab is for students to understand trees and binary trees, and learn algorithms for insertion, search, and traversal of nodes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views19 pages

Lab Manual 13 DSA

The document provides information about trees as a data structure. It defines trees and describes their key components like nodes, edges, root, leaves, internal nodes, etc. It then focuses on binary trees, defining them as trees where each node has at most two children. It describes different types of binary trees including strictly binary trees, where each node has two children or none; complete binary trees, where all levels are fully filled except the lowest; and extended binary trees, which are made full by adding dummy nodes. The objective of the lab is for students to understand trees and binary trees, and learn algorithms for insertion, search, and traversal of nodes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

Student Name Fazeel Ahmad

Student Roll # INFT-18111027

Department
Information Technology

Batch/Year/Section 2018-2022

For Lab. Instructor

Marks Signature

Course: Data Structures & Algorithms

Lab Instructor:
Ms. Humaira Anwer

Department of Computer Science & Information Technology

Khwaja Fareed University of Engineering


& Information Technology,
(KFUEIT)
Abu Dhabi Road,
Rahim Yar Khan.

02/06/2017
Lab Manual Tree
#13 s

Lab Manual # 13
Trees

KFUEIT Department of CS/IT


195
Objective
After performing this lab students would be able to:
1. Understand the concept of tree data structure.
2. Understand the basics of binary tree and binary search tree.
3. Learn and implement algorithms of insertion and search in tree.
4. Learn and implement tree traversals using post-order, pre-order and in-order traversal
techniques.
Trees
In linear data structure, data is organized in sequential order and in non-linear data structure,
data is organized in random order. Tree is a very popular data structure used in wide range of
applications. A tree data structure can be defined as follows :

“Tree is a non-linear data structure which organizes data in hierarchical structure and this
is a recursive definition.”

A tree data structure can also be defined as follows:

“Tree data structure is a collection of data (Node) which is organized in hierarchical


structure and this is a recursive definition.”

Tree represents the nodes connected by edges. A tree data structure can be described as a
collection of nodes (starting at a root node), where each node is a data structure consisting of
a value, together with a list of references to nodes (the "children"), with the constraints that
no reference is duplicated, and none points to the root. Tree is a nonlinear data structure.

The tree with no nodes is called the null or empty tree. A tree that is not empty consists of a
root node and potentially many levels of additional nodes that form a hierarchy. In a tree data
structure, if we have N number of nodes then we can have a maximum of N-1 number of
links.

Fig. 13.1. Representation of a tree


Binary Tree
Binary Tree is a special data structure used for data storage purposes. A binary tree has a
special condition that each node can have a maximum of two children.

A binary tree is made of nodes, where each node contains a "left" pointer, a "right" pointer,
and a data element as shown in fig. 12.2.

Leftchild Data Rightchild

Fig. 13.2. Representation of a node in Binary Tree

The "root" pointer points to the topmost node in the tree. The left and right pointers
recursively point to smaller "subtrees" on either side. A null pointer represents a binary tree
with no elements -- the empty tree.

A binary tree has the benefits of both an ordered array and a linked list as search is as quick
as in a sorted array and insertion or deletion operation are as fast as in linked list.

Fig. 13.2. Simple Binary Tree

Tree Terminology
In a tree data structure,
following terminology is
used:

Root

In a tree data structure, the


first node is called as Root
Node. Every tree must
have root node. It can be
said that root node is the
origin of tree data structure.
In any tree, there must be
only one root node. There
are never multiple root nodes
in a tree.

Edge

In a tree data structure, the


connecting link between any
two nodes is called
as EDGE. In a tree with 'N'
number of nodes there will
be a maximum of 'N-1'
number of edges.

Parent

In a tree data structure, the


node which is predecessor
of any node is called
as PARENT NODE. In
simple words, the node which has branch from it to any other node is called as parent node.
Parent node can also be
defined as "The node which
has child / children".

Child

In a tree data structure, the


node which is descendant of
any node is called as CHILD
Node. In simple words, the
node which has a link
from
its parent node is called as child node. In a tree, any parent node can have any number of
child nodes. In a tree, all the
nodes except root are child
nodes.

Siblings

In a tree data structure, nodes


which belong to same Parent
are called as SIBLINGS. In
simple words, the nodes
with
same parent are called as
Sibling nodes.

Leaf

In a tree data structure, the


node which does not have a
child is called as LEAF
Node. In simple words, a
leaf is a node with no
child. In a tree data structure,
the leaf nodes are also called as External Nodes. External node is also a node with no
child. In a tree, leaf node is also called as 'Terminal' node.

Internal Nodes

In a tree data structure, the


node which has at least one
child is called
as INTERNAL Node. In
simple words, an internal
node is a node with at least
one child. In a tree data
structure, nodes other than
leaf nodes are called
as Internal Nodes. The root node is also said to be Internal Node if the tree has more
than one node. Internal nodes are also called as 'Non-Terminal' nodes.

Degree

In a tree data structure, the


total number of children of a
node is called
as DEGREE of that Node.
In simple words, the Degree
of a node is total number of
children it has. The highest
degree of a node among all
the nodes in a tree is called
as 'Degree of Tree'

Level

In a tree data structure, the root node is said to be at Level 0 and the children of root node are
at Level 1 and the children of the nodes which are at Level 1 will be at Level 2 and so on... In
Lab Manual Tree
#13 s

simple words, in a tree each step


from top to bottom is called as a
Level and the Level count starts
with '0' and incremented by one
at
each level (Step).

13.4.10 Height
.
In a tree data structure, the total
number of egdes from leaf node
to a particular node in the
longest path is called
as HEIGHT of that Node. In a
tree, height of the root node is
said to be height of the
tree. In a tree, height of
all leaf nodes is '0'.
Depth

In a tree data structure, the total


number of egdes from root
node to a particular node is
called as DEPTH of that
Node. In a tree, the total
number of edges from root
node to a leaf node in the
longest path is said to
be Depth of the tree. In
simple words, the highest depth of any leaf node in a tree is said to be depth of that tree. In a
tree, depth of the root node is '0'.

Path

In a tree data structure, the


sequence of Nodes and Edges
from one node to another node is
called as PATH between that
two Nodes. Length of a Path is
total number of nodes in that
path. In below example the path
A - B - E - J has length 4.

KFUEIT Department of CS/IT


200
Lab Manual Tree
#13 s
Sub Tree

In a tree data structure, each child from a


node forms a subtree recursively. Every child
node will form a subtree on its parent node.

Types of Binary Tree


There are different types of binary trees and they are...

Strictly Binary Tree

In a binary tree, every node can have a maximum of two children. But in strictly binary tree,
every node should have exactly two children or none. That means every internal node must
have exactly two children. A strictly
Binary Tree can be defined as follows...

A binary tree in which every node has


either two or zero number of children is
called Strictly Binary Tree.

Strictly binary tree is also called as Full


Binary Tree or Proper Binary Tree or 2-
Tree

Strictly binary tree data structure is used to


represent mathematical expressions.

Complete Binary Tree

In a binary tree, every node can have a maximum


of two children. But in strictly binary tree, every
node should have exactly two children or none and
in complete binary tree all the nodes must have
exactly two children and at every level of
complete binary tree there must be 2level number of
nodes. For example at level 2 there must be 2 2 = 4
nodes and at level 3 there must be 23 = 8 nodes.

KFUEIT Department of CS/IT


201
A binary tree in which every internal node has exactly two children and all leaf nodes are at
same level is called Complete Binary Tree.

Complete binary tree is also called as Perfect Binary Tree.

Extended Binary Tree

A binary tree can be converted into Full Binary tree by adding dummy nodes to existing
nodes wherever required.

The full binary tree obtained by adding dummy nodes to a binary tree is called as Extended
Binary Tree.

In above figure, a normal


binary tree is converted into
full binary tree by adding
dummy nodes (In pink
colour).

Binary Search Tree


A "binary search tree" (BST) or "ordered binary tree" is a type of binary tree where the nodes
are arranged in order: for each node, all elements in its left subtree are less-or-equal to the
parent node (<=), and all the elements in its right subtree are greater than the parent node (>).

In simple words a node's left child must have a value less than its parent's value and the
node's right child must have a value greater than its parent value.

Fig. 12.3. Binary Search Tree

TREE NODE

The code to write a tree node would be similar to what is given below. It has a data part and
references to its left and right child nodes.
1. struct node
2. {
3. int data;
4. node *leftChild;
5. node *rightChild;
6. };

BST Basic Operations

The basic operations that can be performed on a binary search tree data structure are the
following −
1. Insert − Inserts an element in a tree/create a tree.
2. Search − Searches an element in a tree.
3. Preorder Traversal − Traverses a tree in a pre-order manner.
4. Inorder Traversal − Traverses a tree in an in-order manner.
5. Postorder Traversal − Traverses a tree in a post-order manner.

INSERT Operation

Whenever an element is to be inserted, first locate its proper location. Start searching from
the root node, then if the data is less than the key value, search for the empty location in the
left subtree and insert the data. Otherwise, search for the empty location in the right subtree
and insert the data.

INSERT Algorithm:
void insert(int data)

Description: This algorithm INSERTS an ITEM (integer type) in binary


search tree at proper place

1. START
2. SET node *tempNode = new node
3. SET tempNode->data = data
4. SET tempNode->leftChild = NULL
5. SET tempNode->rightChild = NULL
6. DECLARE node *current
7. DECLARE node *parent
//if tree is empty
8. CHECK if(root == NULL)
a. SET root = tempNode
9. else
a. SET current = root
b. parent = NULL
c. REPEAT STEPS i to v while(1)
i. SET parent = current
//go to left of the tree
ii. CHECK if(data < parent->data)
 SET current = current->leftChild
//insert to the left
 CHECK if(current == NULL)
 SET parent->leftChild = tempNode
 return
 END if
iii. END if
//go to right of the tree
iv. else
 SET current = current->rightChild
//insert to the right
 if(current == NULL)
 parent->rightChild = tempNode
 return
 END if
v. END else
d. END while loop step c.
10. END else step 9
11. EXIT

SEARCH Operation
Whenever an element is to be searched, start searching from the root node. Then if the data is
less than the target value, search for the element in the left subtree. Otherwise, search for the
element in the right subtree. Follow the same algorithm for each node.

Search Algorithm:
node* search(int data)
Description: This algorithm searches for a target value in a tree.

1. START
2. SET node *current = root;
3. REPEAT steps a to i while(current->data != data)
a. if(current != NULL)
b. PRINT current->data
//go to left tree
c. if(current->data > data)
i. current = current->leftChild
d. END if
//else go to right tree
e. else
i. current = current->rightChild;
f. END else
//not found
g. CHECK if(current == NULL)
i. return NULL;
h. END if
i. END WHILE loop step 3
j. return current
k. EXIT
PREORDER TRAVERSAL
In this traversal method, the root node is visited first, then the left subtree and finally the right
subtree.

Preorder Algorithm:
void pre_order_traversal(struct node* root)

Description: This algorithm performs preorder traversal on the tree


and generates preordered list of nodes of tree.

1. START
2. CHECK if(root != NULL)THEN
a. PRINT root->data
b. CALL pre_order_traversal(root->leftChild)
c. CALL pre_order_traversal(root->rightChild)
3. END if
4. EXIT

INORDER TRAVERSAL
In this traversal method, the left subtree is visited first, then the root and later the right sub-
tree. We should always remember that every node may represent a subtree itself. If a binary
tree is traversed in-order, the output will produce sorted key values in an ascending order.

Inorder Algorithm:
void inorder_trave rsal(struct node* root)

Description: This algorithm performs inorder traversal on the tree


and generates inordered list of nodes of tree.

1. START
2. CHECK if(root != NULL)THEN
a. CALL inorder_traversal(root->leftChild)
b. PRINT root->data
c. CALL inorder_traversal(root->rightChild)
3. END if
4. EXIT

POSTORDER TRAVERSAL
In this traversal method, the root node is visited last, hence the name. First we traverse the
left subtree, then the right subtree and finally the root node.

Postorder Algorithm:
void post_order_traversal(struct node* root)

Description: This algorithm performs inorder traversal on the tree


and generates inordered list of nodes of tree.

1. START
2. CHECK if(root != NULL)THEN
a. CALL post_order_traversal(root->leftChild)
b. CALL post_order_traversal(root->rightChild)
c. PRINT root->data
3. END if
4. EXIT

LAB TASK

1. Write a single C++ code to implement all discussed algorithms for tree data structure.

Code Area
#include &lt;iostream&gt;
using namespace std;
 
//declaration for new tree node
struct node  {
int data;
struct node *left;
struct node *right;
};
   
//allocates new node
struct node* newNode(int data) {
  // declare and allocate new node 
  struct node* node = new struct node();
   
  node-&gt;data = data;    // Assign data to this node
   
  // Initialize left and right children as NULL
node-&gt;left = NULL;
node-&gt;right = NULL;
return(node);
}
   
int main() {
  /*create root node*/
struct node *rootNode = newNode(10); 
cout&lt;&lt;"General tree created is as follows:"&lt;&lt;endl;
cout&lt;&lt;"\t\t\t "&lt;&lt;rootNode-&gt;data&lt;&lt;endl;
cout&lt;&lt;"\t\t\t "&lt;&lt;"/ "&lt;&lt;"\\"&lt;&lt;endl; rootNode-&gt;left        =
newNode(20);
rootNode-&gt;right       = newNode(30);
cout&lt;&lt;"\t\t\t"&lt;&lt;rootNode-&gt;left-&gt;data&lt;&lt;"  "&lt;&lt;rootNode-
&gt;right-&gt;data;
cout&lt;&lt;endl; rootNode-&gt;left-&gt;left  = newNode(40);
cout&lt;&lt;"\t\t\t"&lt;&lt;"/"&lt;&lt;endl;
cout&lt;&lt;"\t\t      "&lt;&lt;rootNode-&gt;left-&gt;left-&gt;data;
    
return 0;
}

You might also like