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

UNIT-4

NON-LINEAR DATA STRUCTURES – TREES:

Tree Data Structure

We read the linear data structures like an array, linked list, stack and queue in which all the
elements are arranged in a sequential manner. The different data structures are used for
different kinds of data.

Some factors are considered before choosing the data structure:

o We need to choose the data structure depend upon What type of data needs to be
stored
o We need to choose data structure based on time taken or time complexity for
insertion,deletion,searching operations.
o We need to choose data structure based on Memory usage of that data structure

A tree is also one of the data structures that represent hierarchical data. Suppose we want to
show the employees and their positions in the hierarchical form then it can be represented as
shown below:

The above tree shows the organization hierarchy of some company. In the above
structure, john is the CEO of the company, and John has two direct reports named
as Steve and Rohan. Steve has three direct reports named Lee, Bob, Ella where Steve is a
manager. Bob has two direct reports named Sal and Emma. Emma has two direct reports
named Tom and Raj. Tom has one direct report named Bill. This particular logical structure
is known as a Tree. Its structure is similar to the real tree, so it is named a Tree. In this
structure, the root is at the top, and its branches are moving in a downward direction.
Therefore, we can say that the Tree data structure is an efficient way of storing the data in a
hierarchical way.

Some basic terms used in Tree data structure.

Let's consider the tree structure, which is shown below:

In the above structure, each node is labeled with some number. Each arrow shown in the
above figure is known as a link between the two nodes.

o Root: The root node is the topmost node in the tree hierarchy. In other words, the root
node is the one that doesn't have any parent. In the above structure, node numbered 1
is the root node of the tree. If a node is directly linked to some other node, it would
be called a parent-child relationship.
o Child node: If the node is a descendant of any node, then the node is known as a
child node.
o Parent: If the node contains any sub-node, then that node is said to be the parent of
that sub-node.
o Sibling: The nodes that have the same parent are known as siblings.
o Leaf Node:- The node of the tree, which doesn't have any child node, is called a leaf
node. A leaf node is the bottom-most node of the tree. There can be any number of
leaf nodes present in a general tree. Leaf nodes can also be called external nodes.
o Internal nodes: A node has at least one child node known as an internal
o Ancestor node:- An ancestor of a node is any predecessor node on a path from the
root to that node. The root node doesn't have any ancestors. In the tree shown in the
above image, nodes 1, 2, and 5 are the ancestors of node 10.
o Descendant: The immediate successor of the given node is known as a descendant of
a node. In the above figure, 10 is the descendant of node 5.

Properties of Tree data structure

o Number of edges: If there are n nodes, then there would n-1 edges. Each arrow in the
structure represents the link or path. Each node, except the root node, will have at
least one incoming link known as an edge. There would be one link for the parent-
child relationship.
o Depth of node x: The depth of node x can be defined as the length of the path from
the root to the node x. One edge contributes one-unit length in the path. So, the depth
of node x can also be defined as the number of edges between the root node and the
node x. The root node has 0 depth.
o Height of node x: The height of node x can be defined as the longest path from the
node x to the leaf node.

Implementation of Tree

The tree data structure can be created by creating the nodes dynamically with the help of the
pointers. The tree in the memory can be represented as shown below:

The above figure shows the representation of the tree data structure in the memory. In the
above structure, the node contains three fields. The second field stores the data; the first field
stores the address of the left child, and the third field stores the address of the right child.

Applications of trees

The following are the applications of trees:

o Storing naturally hierarchical data: Trees are used to store the data in the
hierarchical structure. For example, the file system. The file system stored on the disc
drive, the file and folder are in the form of the naturally hierarchical data and stored in
the form of trees.
o Organize data: It is used to organize data for efficient insertion, deletion and
searching. For example, a binary tree has a logN time for searching an element.
o Heap: It is also a tree data structure implemented using arrays. It is used to implement
priority queues.
o B-Tree and B+Tree: B-Tree and B+Tree are the tree data structures used to
implement indexing in databases.
o Routing table: The tree data structure is also used to store the data in routing tables in
the routers.

Types of Tree data structure

The following are the types of a tree data structure:

o General tree: The general tree is one of the types of tree data structure. In the general
tree, a node can have either 0 or maximum n number of nodes. There is no restriction
imposed on the degree of the node (the number of nodes that a node can contain). The
topmost node in a general tree is known as a root node. The children of the parent
node are known as subtrees.

There can be n number of subtrees in a general tree. In the general tree, the subtrees are
unordered as the nodes in the subtree cannot be ordered.
Every non-empty tree has a downward edge, and these edges are connected to the nodes
known as child nodes. The root node is labeled with level 0. The nodes that have the same
parent are known as siblings.

Binary tree: Here, binary name itself suggests two numbers, i.e., 0 and 1. In a binary tree,
each node in a tree can have utmost two child nodes. Here, utmost means whether the node
has 0 nodes, 1 node or 2 nodes.
o Binary Search tree: Binary search tree is a non-linear data structure in which one
node is connected to n number of nodes. It is a node-based data structure. A node can
be represented in a binary search tree with three fields, i.e., data part, left-child, and
right-child. A node can be connected to the utmost two child nodes in a binary search
tree, so the node contains two pointers (left child and right child pointer).
Every node in the left sub tree must contain a value less than the value of the root
node, and the value of each node in the right sub tree must be bigger than the value of
the root node.

Binary Tree

A binary tree is 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
Types of Binary Tree

1. Full Binary Tree

A full Binary tree is a special type of binary tree in which every parent node/internal node has
either two or no children.

2. Perfect Binary Tree

A perfect binary tree is a type of binary tree in which every internal node has exactly two
child nodes and all the leaf nodes are at the same level.

3. Complete Binary Tree

A complete binary tree is just like a full binary tree, but with two major differences
1. Every level must be completely filled

2. All the leaf elements must lean towards the left.

3. The last leaf element might not have a right sibling i.e. a complete binary tree doesn't have to
be a full binary tree.

fig which contains red marks it not complete binary tree

fig which contains green marks it is complete binary tree

4. Degenerate or Pathological Tree

A degenerate or pathological tree is the tree having a single child either left or right.
5. Skewed Binary Tree

A skewed binary tree is a pathological/degenerate tree in which the tree is either dominated
by the left nodes or the right nodes. Thus, there are two types of skewed binary tree: left-
skewed binary tree and right-skewed binary tree.

6. Balanced Binary Tree

It is a type of binary tree in which the difference between the height of the left and the right
subtree for each node is either 0 or 1.

Applications of Binary Trees


1. Search algorithms: Binary search algorithms use the structure of binary trees to
efficiently search for a specific element.
2. Sorting algorithms: Binary trees can be used to implement efficient sorting
algorithms, such as tree sort and heap sort.
3. Database systems: Binary trees can be used to store data in a database system, with
each node representing a record. This allows for efficient search operations and
enables the database system to handle large amounts of data.
4. File systems: Binary trees can be used to implement file systems, where each node
represents a directory or file.
5. Compression algorithms: Binary trees can be used to implement Huffman coding, a
compression algorithm that assigns variable-length codes to characters based on their
frequency of occurrence in the input data.
6. Decision trees: Binary trees can be used to implement decision trees.
7. Game AI: Binary trees can be used to implement game AI, where each node
represents a possible move in the game. The AI algorithm can search the tree to find
the best possible move.
Advantages of Binary Trees
1. Efficient searching: Binary trees are particularly efficient when searching for a
specific element, as each node has at most two child nodes, allowing for binary
search algorithms to be used.
2. Ordered traversal: The structure of binary trees enables them to be traversed in a
specific order, such as in-order traversal, pre-order traversal, and post-order
traversal.
3. Memory efficiency: Compared to other tree structures, binary trees are relatively
memory-efficient because they only require two child pointers per node.
4. Easy to implement: Binary trees are relatively easy to implement and understand,
making them a popular choice for a wide range of applications.
Properties of Binary Tree

1. The maximum number of nodes at level ‘l’ of a binary tree is 2 l:


2. The Maximum number of nodes in a binary tree of height ‘h’ is 2 h – 1:
3. In a non-empty binary tree, if n is the total number of nodes and e is the total
number of edges, then e = n-1:
Binary Tree Travels

Traversal is a process to visit all the nodes of a tree and may print their values too. Because,
all nodes are connected via edges (links) we always start from the root (head) node. That is,
we cannot randomly access a node in a tree. There are three ways which we use to traverse a
tree −

 In-order Traversal
 Pre-order Traversal
 Post-order Traversal
Generally, we traverse a tree to search or locate a given item or key in the tree or to print all
the values it contains.

In-order Traversal(LEFT CHILD-ROOT-RIGHT CHILD)

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.

Example-2
If a binary tree is traversed in-order, the output will produce sorted key values in an
ascending order.

We start from A, and following in-order traversal, we move to its left subtree B.B is also
traversed in-order. The process goes on until all the nodes are visited. The output of in-order
traversal of this tree will be −
D→B→E→A→F→C→G

Example-2

The inorder printing sequence will be 23, 211, 89, 18, 10, 20, 32.

Example-3

After the completion of inorder traversal, the final output is -

{15, 25, 28, 30, 35, 40, 45, 50, 55, 60, 70}

Algorithm

Until all nodes are traversed –

Step 1 − Recursively traverse left subtree.


Step 2 − Visit root node.Algorithm

Until all nodes are traversed −

Step 3 − Recursively traverse right subtree.

Pre-order Traversal

In this traversal method, the root node is visited first, then the left sub-tree and finally the
right sub-tree.

We start from A, and following pre-order traversal, we first visit A itself and then move to its
left subtree B. B is also traversed pre-order. The process goes on until all the nodes are
visited. The output of pre-order traversal of this tree will be −

A→B→D→E→C→F→G

Example-2
After the completion of preorder traversal, the final output is -

40, 30, 25, 15, 28, 35, 50, 45, 60, 55, 70

Algorithm

Until all nodes are traversed −

Step 1 − Visit root node.

Step 2 − Recursively traverse left subtree.

Step 3 − Recursively traverse right subtree.

Post-order 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.
We start from A, and following pre-order traversal, we first visit the left subtree B. B is also
traversed post-order. The process goes on until all the nodes are visited. The output of post-
order traversal of this tree will be −

D→E→B→F→G→C→A

Algorithm

Until all nodes are traversed −

Step 1 − Recursively traverse left subtree.

Step 2 − Recursively traverse right subtree.

Step 3 − Visit root node.

Example-2 post order traversal

The final output that we will get after postorder traversal is -

{15, 28, 25, 35, 30, 45, 55, 70, 60, 50, 40}

Insertion in a Binary Tree in level order


Given a binary tree and a key, insert the key into the binary tree at the first position
available in level order
Deletion in a Binary Tree
Algorithm:
1. Starting at the root, find the deepest and rightmost node in the binary tree and the node
which we want to delete.
2. Replace the deepest rightmost node’s data with the node to be deleted.
3. Then delete the deepest rightmost node.

What is a Binary Search tree?

A binary search tree follows some order to arrange the elements. In a Binary search tree, the
value of left node must be smaller than the parent node, and the value of right node must be
greater than the parent node. This rule is applied recursively to the left and right subtrees of
the root.

Let's understand the concept of Binary search tree with an example.


In the above figure, we can observe that the root node is 40, and all the nodes of the left sub-
tree are smaller than the root node, and all the nodes of the right sub-tree are greater than the
root node.

Similarly, we can see the left child of root node is greater than its left child and smaller than
its right child. So, it also satisfies the property of binary search tree. Therefore, we can say
that the tree in the above image is a binary search tree.

Suppose if we change the value of node 35 to 55 in the above tree, check whether the tree
will be binary search tree or not.

In the above tree, the value of root node is 40, which is greater than its left child 30 but
smaller than right child of 30, i.e., 55. So, the above tree does not satisfy the property of
Binary search tree. Therefore, the above tree is not a binary search tree.

Advantages of Binary search tree


o Searching an element in the Binary search tree is easy as we always have a hint that
which subtree has the desired element.
o As compared to array and linked lists, insertion and deletion operations are faster in
BST.
Example of creating a binary search tree

Now, let's see the creation of binary search tree using an example.

Suppose the data elements are - 45, 15, 79, 90, 10, 55, 12, 20, 50

o First, we have to insert 45 into the tree as the root of the tree.
o Then, read the next element; if it is smaller than the root node, insert it as the root of
the left subtree, and move to the next element.
o Otherwise, if the element is larger than the root node, then insert it as the root of the
right subtree.

Now, let's see the process of creating the Binary search tree using the given data element. The
process of creating the BST is shown below -

Step 1 - Insert 45.

Step 2 - Insert 15.

As 15 is smaller than 45, so insert it as the root node of the left subtree.

Step 3 - Insert 79.

As 79 is greater than 45, so insert it as the root node of the right subtree.
Step 4 - Insert 90.

90 is greater than 45 and 79, so it will be inserted as the right subtree of 79.

ADVERTISEMENT

Step 5 - Insert 10.

10 is smaller than 45 and 15, so it will be inserted as a left subtree of 15.

Step 6 - Insert 55.

55 is larger than 45 and smaller than 79, so it will be inserted as the left subtree of 79.
Step 7 - Insert 12.

12 is smaller than 45 and 15 but greater than 10, so it will be inserted as the right subtree of
10.

Step 8 - Insert 20.

20 is smaller than 45 but greater than 15, so it will be inserted as the right subtree of 15.

Step 9 - Insert 50.

50 is greater than 45 but smaller than 79 and 55. So, it will be inserted as a left subtree of 55.
Now, the creation of binary search tree is completed. After that, let's move towards the
operations that can be performed on Binary search tree.

We can perform insert, delete and search operations on the binary search tree.

Let's understand how a search is performed on a binary search tree.

Insertion in Binary Search tree

A new key in BST is always inserted at the leaf. To insert an element in BST, we have to start
searching from the root node; if the node to be inserted is less than the root node, then search
for an empty location in the left sub-tree. Else, search for the empty location in the right sub-
tree and insert the data. Insert in BST is similar to searching, as we always have to maintain
the rule that the left sub-tree is smaller than the root, and right sub-tree is larger than the root.

Now, let's see the process of inserting a node into BST using an example.
Deletion in Binary Search tree

In a binary search tree, we must delete a node from the tree by keeping in mind that the
property of BST is not violated. To delete a node from BST, there are three possible
situations occur -

o The node to be deleted is the leaf node, or,


o The node to be deleted has only one child, and,
o The node to be deleted has two children

We will understand the situations listed above in detail.

When the node to be deleted is the leaf node

It is the simplest case to delete a node in BST. Here, we have to replace the leaf node with
NULL and simply free the allocated space.

We can see the process to delete a leaf node from BST in the below image. In below image,
suppose we have to delete node 90, as the node to be deleted is a leaf node, so it will be
replaced with NULL, and the allocated space will free.
When the node to be deleted has only one child

In this case, we have to replace the target node with its child, and then delete the child node.
It means that after replacing the target node with its child node, the child node will now
contain the value to be deleted. So, we simply have to replace the child node with NULL and
free up the allocated space.

We can see the process of deleting a node with one child from BST in the below image. In
the below image, suppose we have to delete the node 79, as the node to be deleted has only
one child, so it will be replaced with its child 55.

So, the replaced node 79 will now be a leaf node that can be easily deleted.

When the node to be deleted has two children

This case of deleting a node in BST is a bit complex among other two cases. In such a case,
the steps to be followed are listed as follows -

o First, find the in order successor of the node to be deleted.


o After that, replace that node with the in order successor until the target node is placed
at the leaf of tree.
o And at last, replace the node with NULL and free up the allocated space.

The in order successor is required when the right child of the node is not empty. We can
obtain the in order successor by finding the minimum element in the right child of the node.
We can see the process of deleting a node with two children from BST in the below image. In
the below image, suppose we have to delete node 45 that is the root node, as the node to be
deleted has two children, so it will be replaced with its in order successor. Now, node 45 will
be at the leaf of the tree so that it can be deleted easily.

Now let's understand how insertion is performed on a binary search tree.

Searching in Binary search tree

Searching means to find or locate a specific element or node in a data structure. In Binary
search tree, searching a node is easy because elements in BST are stored in a specific order.
The steps of searching a node in Binary Search tree are listed as follows -

1. First, compare the element to be searched with the root element of the tree.
2. If root is matched with the target element, then return the node's location.
3. If it is not matched, then check whether the item is less than the root element, if it is
smaller than the root element, then move to the left subtree.
4. If it is larger than the root element, then move to the right subtree.
5. Repeat the above procedure recursively until the match is found.
6. If the element is not found or not present in the tree, then return NULL.

Now, let's understand the searching in binary tree using an example. We are taking the binary
search tree formed above. Suppose we have to find node 20 from the below tree.

Step1:
Step2:

Step3:

Now, let's see the algorithm to search an element in the Binary search tree.

The complexity of the Binary Search tree

Let's see the time and space complexity of the Binary search tree. We will see the time
complexity for insertion, deletion, and searching operations in best case, average case, and
worst case.
1. Time Complexity
Operations Best case time Average case time Worst case time
complexity complexity complexity

Insertion O(log n) O(log n) O(n)

Deletion O(log n) O(log n) O(n)

Search O(log n) O(log n) O(n)

Where 'n' is the number of nodes in the given tree.

2. Space Complexity
Operations Space complexity

Insertion O(n)

Deletion O(n)

Search O(n)

o The space complexity of all operations of Binary search tree is O(n).

To create a binary tree from its in-order and either pre-order or post-order traversals, you can
follow these steps:

1. Understand the Traversals:


 In-order: Left subtree, root, right subtree.
 Pre-order: Root, left subtree, right subtree.
 Post-order: Left subtree, right subtree, root.
2. Identify the Root:
 In pre-order, the first element is the root.
 In post-order, the last element is the root.
3. Locate Root in In-order:
 The root separates the in-order traversal into left and right subtrees.
4. Recursively Build Left and Right Subtrees:
 Use the left and right parts of the in-order traversal to find the elements for the left
and right subtrees in the pre-order or post-order traversal.
Example-1
Construct Tree from given Inorder and Preorder traversals

Let us consider the below traversals:


 Inorder sequence: D B E A F C
 Preorder sequence: A B D E C F
 In a Preorder sequence, the leftmost element is the root of the tree. So we know ‘A’
is the root for given sequences. By searching ‘A’ in the Inorder sequence, we can
find out all elements on the left side of ‘A’ is in the left subtree and elements on
right in the right subtree. So we know the below structure now.

We recursively follow the above steps and get the following tree.

Example-2

Consider a binary tree from inorder 9,3,15,20,7 and preorder 3,9,20,15,7


sequence
Given preorder sequence 3,9,20,15,7
Inorder sequence:9,3,15,20,7
Example-3

Algorithm: buildTree()
1. Pick an element from Preorder. Increment a Preorder Index Variable (preIndex in
below code) to pick the next element in the next recursive call.
2. Create a new tree node tNode with the data as the picked element.
3. Find the picked element’s index in Inorder. Let the index be inIndex.
4. Call buildTree for elements before inIndex and make the built tree as a left subtree of
tNode.
5. Call buildTree for elements after inIndex and make the built tree as a right subtree of
tNode.
6. return tNode.

Construct binary Tree from given Inorder and Postorder traversals


Example-1
construct a binary tree from in-order[] = {4, 8, 2, 5, 1, 6, 3, 7} and post-order[] = {8, 4, 5,
2, 6, 7, 3, 1}:
Example-2

Given Inorder sequence 40,20,50,10,60,30 and

PostOrder sequence 40,50,20,60,30,10 of a binary tree, we need to construct the unique


binary tree represented by them.

Example -3
Input: 'inOrder' = [9, 3, 15, 20, 7], 'postOrder' = [9, 15, 7, 20, 3]

Output:
We get the following binary tree from Inorder and Postorder traversal:
Example-4
Given
post order sequence 4 5 2 6 7 3 1
Inorder sequence 4 2 5 1 6 3 7

Example-5

Post order sequence 2 9 3 6 10 5


in order sequence 2 6 3 9 5 10

You might also like