0% found this document useful (0 votes)
122 views49 pages

Non-Broom Trees and Subtree Concepts

This document provides an overview of tree data structures, defining trees as non-linear structures that organize data hierarchically. It explains key terminology related to trees, such as root, edge, parent, child, and various types of trees including binary trees and their specific forms like strictly binary and complete binary trees. Additionally, it discusses representations of trees, including array and linked list methods, and introduces the concept of binary search trees which optimize search operations.

Uploaded by

Irfan Nanasana
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
122 views49 pages

Non-Broom Trees and Subtree Concepts

This document provides an overview of tree data structures, defining trees as non-linear structures that organize data hierarchically. It explains key terminology related to trees, such as root, edge, parent, child, and various types of trees including binary trees and their specific forms like strictly binary and complete binary trees. Additionally, it discusses representations of trees, including array and linked list methods, and introduces the concept of binary search trees which optimize search operations.

Uploaded by

Irfan Nanasana
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

UNIT-5

NON LINEAR DATA STUCTURES


-TREES
5.1. DEFINE TREES
In linear data structure data is organized in sequential order and in non-linear data structure data
is organized in random order. A tree is a very popular non-linear data structure used in a 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 recursively
In tree data structure, every individual element is called as Node. Node in a tree data structure
stores the actual data of that particular element and link to next element in hierarchical structure.

In a tree data structure, if we have N number of nodes then we can have a maximum of N-
1 number of links.

EXAMPLE:

A tree is a non-linear abstract data type with a hierarchy-based structure. It consists of nodes
(where the data is stored) that are connected via links. The tree data structure stems from a
single node called a root node and has subtrees connected to the root.
5.1.1 Explain the terminology related to Tree (Root, Edge, Parent,
Child, Siblings, Leaf, Internal nodes, Degree, Level, Height, Depth,
Path, Sub tree, Forest).

Terminology
In a tree data structure, we use the following terminology...

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

2. 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.
3. Parent
In a tree data structure, the node which is a predecessor of any node is called as PARENT NODE.
In simple words, the node which has a branch from it to any other node is called a parent node.
Parent node can also be defined as "The node which has child / children".

4. 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
5. Siblings
In a tree data structure, nodes which belong to same Parent are called as SIBLINGS. In simple
words, the nodes with the same parent are called Sibling nodes.

6. 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.

7. Internal Nodes
In a tree data structure, the node which has atleast one child is called as INTERNAL Node. In
simple words, an internal node is a node with atleast 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.
8. 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'

9. 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 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).
10. Height
In a tree data structure, the total number of edges 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'.

11. 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'.

12. 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.
13. 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.

13. Forest:
A collection of disjoint trees is called a forest.
Tree Representations

A tree data structure can be represented in two methods. Those methods are as follows...

1. List Representation

2. Left Child - Right Sibling Representation

Consider the following tree...

1. List Representation

In this representation, we use two types of nodes one for representing the node with data called

'data node' and another for representing only references called 'reference node'. We start with a

'data node' from the root node in the tree. Then it is linked to an internal node through a 'reference

node' which is further linked to any other node directly. This process repeats for all the nodes in

the tree.

The above example tree can be represented using List representation as follows...
2. Left Child - Right Sibling Representation

In this representation, we use a list with one type of node which consists of three fields namely

Data field, Left child reference field and Right sibling reference field. Data field stores the actual

value of a node, left reference field stores the address of the left child and right reference field

stores the address of the right sibling node. Graphical representation of that node is as follows...

In this representation, every node's data field stores the actual value of that node. If that node has
left a child, then left reference field stores the address of that left child node otherwise stores NULL.
If that node has the right sibling, then right reference field stores the address of right sibling node
otherwise stores NULL.
The above example tree can be represented using Left Child - Right Sibling representation as
follows...
5.2 Define Binary Tree

Binary Tree Datastructure

In a normal tree, every node can have any number of children. A binary tree is a special type of

tree data structure in which every node can have a maximum of 2 children. One is known as a

left child and the other is known as right child.

A tree in which every node can have a maximum of two children is called Binary Tree.

In a binary tree, every node can have either 0 children or 1 child or 2 children but not more than 2

children.

Example

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

1. 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.

Example

2. 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 22 = 4 nodes and at level 3 there must be 23 = 8 nodes.

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


3. 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).

5.3 Write the differences between General Tree and Binary Tree
General tree Binary tree

General tree is a tree in


Whereas in binary tree, each node can have
which each node can have
at most two nodes.
many children or nodes.

The subtree of a general tree


While the subtree of binary tree hold the
do not hold the ordered
ordered property.
property.

In data structure, a general


While it can be empty.
tree can not be empty.

In general tree, a node can


While in binary tree, a node can have at
have at most n(number of
most 2(number of child nodes) nodes.
child nodes) nodes.
General tree Binary tree

While in binary tree, there is limitation on the


In general tree, there is no
degree of a node because the nodes in a
limitation on the degree of a
binary tree can’t have more than two child
node.
node.

In general tree, there is


While in binary tree, there are mainly two
either zero subtree or many
subtree: Left-subtree and Right-subtree.
subtree.

5.4 Convert General Trees to Binary Trees


Following are the rules to convert a Generic(N-array Tree) to a Binary
Tree:
 The root of the Binary Tree is the Root of the Generic Tree.
 The left child of a node in the Generic Tree is the Left child of that node
in the Binary Tree.
 The right sibling of any node in the Generic Tree is the Right child of
that node in the Binary Tree.
Examples:
Convert the following Generic Tree to Binary Tree:
Examples:
Convert the following Generic Tree to Binary Tree:

Construct Binary Tree from Parent Array


Below are the steps for the conversion of Generic Tree to Binary Tree:
1. As per the rules mentioned above, the root node of general tree A is
the root node of the binary tree.
2. Now the leftmost child node of the root node in the general tree
is B and it is the leftmost child node of the binary tree.
3. Now as B has E as its leftmost child node, so it is its leftmost child
node in the binary tree whereas it has C as its rightmost sibling node
so it is its right child node in the binary tree.
4. Now C has F as its leftmost child node and D as its rightmost sibling
node, so they are its left and right child node in the binary tree
respectively.
5. Now D has I as its leftmost child node which is its left child node in the
binary tree but doesn’t have any rightmost sibling node, so doesn’t
have any right child in the binary tree.
6. Now for I, J is its rightmost sibling node and so it is its right child node
in the binary tree.
7. Similarly, for J, K is its leftmost child node and thus it is its left child
node in the binary tree.
8. Now for C, F is its leftmost child node, which has G as its rightmost
sibling node, which has H as its just right sibling node and thus they
form their left, right, and right child node respectively.

Below is the Binary Tree of the above Generic Tree:

Note: If the parent node has only the right child in the general tree then it
becomes the rightmost child node of the last node following the parent
node in the binary tree. In the above example, if node B has the right child
node L then in binary tree representation L would be the right child of
node D.
5.5 Explain the linear representation and linked list representation of
a Binary Tree

Binary Tree Representations

A binary tree data structure is represented using two methods. Those methods are as follows...

1. Array Representation

2. Linked List Representation

Consider the following binary tree...

1. Array Representation of Binary Tree

In array representation of a binary tree, we use one-dimensional array (1-D Array) to represent a

binary tree.

Consider the above example of a binary tree and it is represented as follows...

To represent a binary tree of depth 'n' using array representation, we need one dimensional array

with a maximum size of 2n + 1.

Sequential representation of Binary Trees-


This representation uses only a single linear array Tree as follows:

 The root R of T is stored in TREE[1]


 If a node N occupies TREE[K], then its left child is stored in TREE[2*K] and its right child is
stored in TREE[2*K+1]
 It can be seen that a sequential representation of a binary tree requires numbering of nodes;
starting with nodes on level 1, then on level 2, and so on. The nodes are numbered from left to
right.
 It is an ideal case for the representation of a complete binary tree and in this case, no space is
wasted. However, for other binary trees, most of the space remains unutilized. As can be seen
in the figure, we require 14 locations in the array even though the tree has only 9 nodes. If null
entries for successors of the terminal nodes are included, we would actually require 29 locations
instead of 14. Thus sequential representation is usually inefficient unless the binary tree is
complete or nearly complete.

2. Linked List Representation of Binary Tree


We use a double linked list to represent a binary tree. In a double linked list, every node consists of
three fields. First field for storing left child address, second for storing actual data and third for
storing right child address.
In this linked list representation, a node has the following structure...
The above example of the binary tree represented using Linked list representation is shown as

follows...

 In linked representation, Tree is maintained in memory by means of three parallel arrays, INFO,
LEFT, and RIGHT, and a pointer variable ROOT.
 Each node N of T will correspond to a location K such that INFO[K] contains data at node
N. LEFT[K] contains the location of the left child of node N and RIGHT[K] contains the location
of right child of node N.
 ROOT will contain the location of root R of Tree. If any subtree is empty, the corresponding
pointer will contain a null value. If the tree T itself is empty, then ROOT will contain a null value
5.6 Define Binary Search Tree

Binary Search tree


In a binary tree, every node can have a maximum of two children but there is no need to maintain
the order of nodes basing on their values. In a binary tree, the elements are arranged in the order
they arrive at the tree from top to bottom and left to right.

A binary tree has the following time complexities...

1. Search Operation - O(n)


2. Insertion Operation - O(1)
3. Deletion Operation - O(n)

To enhance the performance of binary tree, we use a special type of binary tree known as Binary
Search Tree. Binary search tree mainly focuses on the search operation in a binary tree. Binary
search tree can be defined as follows...

Binary Search Tree is a binary tree in which every node contains only smaller values in its
left subtree and only larger values in its right subtree.
In a binary search tree, all the nodes in the left subtree of any node contains smaller values and
all the nodes in the right subtree of any node contains larger values as shown in the following
figure...

Example
The following tree is a Binary Search Tree. In this tree, left subtree of every node contains nodes
with smaller values and right subtree of every node contains larger values.
Every binary search tree is a binary tree but every binary tree need not to be binary search
tree.

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.

In the above figure, we can observe that the root node is 40, and all the nodes of the left
subtree are smaller than the root node, and all the nodes of the right subtree 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.

Operations on a Binary Search Tree


The following operations are performed on a binary search tree...

1. Search
2. Insertion
3. Deletion

Search Operation in BST


In a binary search tree, the search operation is performed with O(log n) time complexity. The
search operation is performed as follows...

 Step 1 - Read the search element from the user.


 Step 2 - Compare the search element with the value of root node in the tree.
 Step 3 - If both are matched, then display "Given node is found!!!" and terminate the
function
 Step 4 - If both are not matched, then check whether search element is smaller or larger
than that node value.
 Step 5 - If search element is smaller, then continue the search process in left subtree.
 Step 6- If search element is larger, then continue the search process in right subtree.
 Step 7 - Repeat the same until we find the exact element or until the search element is
compared with the leaf node
 Step 8 - If we reach to the node having the value equal to the search value then display
"Element is found" and terminate the function.
 Step 9 - If we reach to the leaf node and if it is also not matched with the search element,
then display "Element is not found" and terminate the function.

Insertion Operation in BST


In a binary search tree, the insertion operation is performed with O(log n) time complexity. In
binary search tree, new node is always inserted as a leaf node. The insertion operation is
performed as follows...
 Step 1 - Create a newNode with given value and set its left and right to NULL.
 Step 2 - Check whether tree is Empty.
 Step 3 - If the tree is Empty, then set root to newNode.
 Step 4 - If the tree is Not Empty, then check whether the value of newNode
is smaller or larger than the node (here it is root node).
 Step 5 - If newNode is smaller than or equal to the node then move to its left child. If
newNode is larger than the node then move to its right child.
 Step 6- Repeat the above steps until we reach to the leaf node (i.e., reaches to NULL).
 Step 7 - After reaching the leaf node, insert the newNode as left child if the newNode
is smaller or equal to that leaf node or else insert it as right child.

Deletion Operation in BST


In a binary search tree, the deletion operation is performed with O(log n) time complexity. Deleting
a node from Binary search tree includes following three cases...

 Case 1: Deleting a Leaf node (A node with no children)


 Case 2: Deleting a node with one child
 Case 3: Deleting a node with two children

Case 1: Deleting a leaf node


We use the following steps to delete a leaf node from BST...

 Step 1 - Find the node to be deleted using search operation


 Step 2 - Delete the node using free function (If it is a leaf) and terminate the function.

Case 2: Deleting a node with one child


We use the following steps to delete a node with one child from BST...

 Step 1 - Find the node to be deleted using search operation


 Step 2 - If it has only one child then create a link between its parent node and child node.
 Step 3 - Delete the node using free function and terminate the function.

Case 3: Deleting a node with two children


We use the following steps to delete a node with two children from BST...

 Step 1 - Find the node to be deleted using search operation


 Step 2 - If it has two children, then find the largest node in its left subtree (OR)
the smallest node in its right subtree.
 Step 3 - Swap both deleting node and node which is found in the above step.
 Step 4 - Then check whether deleting node came to case 1 or case 2 or else goto step 2
 Step 5 - If it comes to case 1, then delete using case 1 logic.
 Step 6- If it comes to case 2, then delete using case 2 logic.
 Step 7 - Repeat the same process until the node is deleted from the tree.

Example
Construct a Binary Search Tree by inserting the following sequence of numbers...
10,12,5,4,20,8,7,15 and 13
Above elements are inserted into a Binary Search Tree as follows...

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.
5.7 Write differences between Binary Search Tree and Binary Tree
Basis for Binary tree Binary search tree
comparison

A binary tree is a non-linear data


structure in which a node can A Binary search tree is a tree that
follows some order to arrange the
have utmost two children, i.e., a
elements, whereas the binary tree does
node can have 0, 1 or maximum
Definition not follow any order. In a Binary search
two children. A binary search tree
tree, the value of the left node must be
is an ordered binary tree in which
smaller than the parent node, and the
some order is followed to organize
value of the right node must be greater
the nodes in a tree. than the parent node.

The structure of the binary tree is


that the first node or the topmost The binary search tree is one of
node is known as the root node. the types of binary tree that has
Each node in a binary tree the value of all the nodes in the
contains the left pointer and the left subtree lesser or equal to the
Structure
right pointer. The left pointer root node, and the value of all the
contains the address of the left nodes in a right subtree are
subtree, whereas right pointer greater than or equal to the value
contains the address of right of the root node.
subtree.

Binary search trees are the


sorted binary trees that provide
The operations that can be fast insertion, deletion and
Operations implemented on a binary tree are search. Lookups mainly
insertion, deletion, and traversal. implement binary search as all
the keys are arranged in sorted
order.

Four types of binary trees are Full


Binary Tree, Complete Binary There are different types of binary
types search trees such as AVL trees,
Tree, Perfect Binary Tree, and
Splay tree, Tango trees, etc.
Extended Binary Tree.
(OR)
Feature Binary Tree Binary Search Tree ( BST )

A binary tree in which for each


A tree data
node, all elements in its left
structure where
subtree are less than the node,
each node can have
and all elements in its right
at most two children
subtree are greater than the
nodes.
Definition node.

Nodes are inserted Nodes are inserted according to


without any specific their values, maintaining the
Node Insertion order. BST property.

No specific order; Efficient lookup using the binary


full tree traversal search property, reducing the
Node may be needed to search space by half at each
Lookup/Search find a node. step.

O(n) for insertion,


Time Complexity O(h) for insertion, deletion, and
deletion, and
search, where h is height.
(average case) search.

O(n) as it only
depends on the O(n) as it only depends on the
Space number of nodes in number of nodes in the tree.
Complexity the tree.

Used in various Ideal for applications where


tree-related efficient search, insertion, and
algorithms and data deletion are required, such as in
Application structures. databases and dictionaries
5.8 Perform various traversals on Binary Trees

Binary Tree Traversals

When we wanted to display a binary tree, we need to follow some order in which all the nodes of

that binary tree must be displayed. In any binary tree, displaying order of nodes depends on the

traversal method.

Displaying (or) visiting order of nodes in a binary tree is called as Binary Tree Traversal.

Tree Traversal refers to the process of visiting or accessing each node of the tree exactly once in a

certain order. Tree traversal algorithms help us to visit and process all the nodes of the tree. Since

tree is not a linear data structure, there are multiple nodes which we can visit after visiting a certain

node. There are multiple tree traversal techniques which decide the order in which the nodes of the

tree are to be visited.

There are three types of binary tree traversals.

1. In - Order Traversal

2. Pre - Order Traversal

3. Post - Order Traversal

Consider the following binary tree...


1. In - Order Traversal ( LeftChild - Root - RightChild )
In In-Order traversal, the root node is visited between the left child and right child. In this traversal,
the left child node is visited first, then the root node is visited and later we go for visiting the right
child node. This in-order traversal is applicable for every root node of all subtrees in the tree. This is
performed recursively for all nodes in the tree.

Inorder Traversal:
Inorder traversal visits the node in the order: Left -> Root -> Right

Algorithm for Inorder Traversal:


Inorder(tree)
 Traverse the left subtree, i.e., call Inorder(left->subtree)
 Visit the root.
 Traverse the right subtree, i.e., call Inorder(right->subtree)

Time Complexity: O(N)


Auxiliary Space: If we don’t consider the size of the stack for function
calls then O(1) otherwise O(h) where h is the height of the tree.
In the above example of a binary tree, first we try to visit left child of root node 'A', but A's left child
'B' is a root node for left subtree. so we try to visit its (B's) left child 'D' and again D is a root for
subtree with nodes D, I and J. So we try to visit its left child 'I' and it is the leftmost child. So first we
visit 'I' then go for its root node 'D' and later we visit D's right child 'J'. With this we have completed
the left part of node B. Then visit 'B' and next B's right child 'F' is visited. With this we have
completed left part of node A. Then visit root node 'A'. With this we have completed left and root
parts of node A. Then we go for the right part of the node A. In right of A again there is a subtree
with root C. So go for left child of C and again it is a subtree with root G. But G does not have left
part so we visit 'G' and then visit G's right child K. With this we have completed the left part of node
C. Then visit root node 'C' and next visit C's right child 'H' which is the rightmost child in the tree. So
we stop the process.

That means here we have visited in the order of I - D - J - B - F - A - G - K - C - H using In-Order


Traversal.

In-Order Traversal for above example of binary tree is

I-D-J-B-F-A-G-K-C–H

2. Pre - Order Traversal ( root - leftChild - rightChild )


In Pre-Order traversal, the root node is visited before the left child and right child nodes. In this
traversal, the root node is visited first, then its left child and later its right child. This pre-order
traversal is applicable for every root node of all subtrees in the tree.

Preorder Traversal:
Preorder traversal visits the node in the order: Root -> Left -> Right
Algorithm for Preorder Traversal:
Preorder(tree)
 Visit the root.
 Traverse the left subtree, i.e., call Preorder(left->subtree)
 Traverse the right subtree, i.e., call Preorder(right->subtree)

Time Complexity: O(N)


Auxiliary Space: If we don’t consider the size of the stack for function
calls then O(1) otherwise O(h) where h is the height of the tree.

In the above example of binary tree, first we visit root node 'A' then visit its left child 'B' which is a
root for D and F. So we visit B's left child 'D' and again D is a root for I and J. So we visit D's left
child 'I' which is the leftmost child. So next we go for visiting D's right child 'J'. With this we have
completed root, left and right parts of node D and root, left parts of node B. Next visit B's right
child 'F'. With this we have completed root and left parts of node A. So we go for A's right
child 'C' which is a root node for G and H. After visiting C, we go for its left child 'G' which is a root
for node K. So next we visit left of G, but it does not have left child so we go for G's right child 'K'.
With this, we have completed node C's root and left parts. Next visit C's right child 'H' which is the
rightmost child in the tree. So we stop the process.

That means here we have visited in the order of A-B-D-I-J-F-C-G-K-H using Pre-Order Traversal.
Pre-Order Traversal for above example binary tree is

A-B-D-I-J-F-C-G-K-H

3. Post - Order Traversal ( leftChild - rightChild - root )


In Post-Order traversal, the root node is visited after left child and right child. In this traversal, left
child node is visited first, then its right child and then its root node. This is recursively performed
until the right most node is visited.

Postorder Traversal:
Postorder traversal visits the node in the order: Left -> Right -> Root

Algorithm for Postorder Traversal:


Algorithm Postorder(tree)
 Traverse the left subtree, i.e., call Postorder(left->subtree)
 Traverse the right subtree, i.e., call Postorder(right->subtree)
 Visit the root

 Time Complexity: O(N)


Auxiliary Space: If we don’t consider the size of the stack for
function calls then O(1) otherwise O(h) where h is the height of the
tree.
Here we have visited in the order of I - J - D - F - B - K - G - H - C - A using Post-Order Traversal.

Post-Order Traversal for above example binary tree is

I-J-D-F-B-K-G-H-C–A

5.9 Construct a Binary Tree using In-order and Preorder Traversals:


Consider the following steps:

1. Find the root node: Use the preorder traversal to find the root node.
2. Find the left and right subtrees: Use the inorder traversal to find the left and right
subtrees by finding the index of the root node of each subtree.
3. Recurse: Recurse down the left and right subtrees, repeating the process until you
find a single element in each subarray.

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.
A
/ \
/ \
D B E F C

We recursively follow the above steps and get the following tree.
A
/ \
/ \
B C
/ \ /
/ \ /
D E F
5.10 Construct a Binary Tree using In-order and Post-order Traversals

Consider following steps:

1. Identify the root node: The last element in the postorder list is the root node.
2. Find the root node's position: Use the inorder list to find the position of the root node.
3. Partition the inorder list: Use the root node's position to split the inorder list into left
and right subtrees.
4. Recursively build the subtrees: Use the left and right partitions of the inorder and
postorder lists to recursively build the left and right subtrees.
5. Repeat: Repeat the process until all nodes are processed and the tree is
reconstructed

Examples:
Input:
in[] = {2, 1, 3}
post[] = {2, 3, 1}
Output: Root of below tree
1
/ \
2 3
Input:
in[] = {4, 8, 2, 5, 1, 6, 3, 7}
post[] = {8, 4, 5, 2, 6, 7, 3, 1}
Output: Root of below tree
1
/ \
2 3
/ \ / \
4 5 6 7
\
8

5.11 Know the importance of Binary Search Trees over General Trees
A Binary search tree (BST) is a type of binary tree that’s more efficient than a general tree in several
ways:

Fast operations: BSTs are faster than arrays and linked lists for most operations including
searching, insertion , and deletion.

No value shifting:BSTs perform operations without having to shift values in memory.


Proportional lookup performance: The lookup performance of a BST is proportional to that
of binary logarithm because each comparison skips about half of the remaining tree.

Easier code:BSTs have easier code than lined lists.


Balanced BSTs are more efficient: Balanced BSTs ,like AVL trees, m-trees, and Red-Black
trees, are more efficient than unbalanced BSTs.

5.12 Perform insertion, deletion, search and various traversal


operations on a Binary Search Tree.
Operations on binary search tree:
 Insertion
 Deletion
 Searching
 Traversal
1. Inorder traversal
2. Preorder traversal
3. Post order traversal

Example of creating a binary search tree


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.
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.

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 1

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.

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 subtree. Else, search for the empty location
in the right subtree and insert the data. Insert in BST is similar to searching, as we always
have to maintain the rule that the left subtree is smaller than the root, and right subtree is
larger than the root.
ALGORITHM:

[Link]

[Link] the tree is empty,insert the first element as the root node of the [Link] following elements are
added as the leaf nodes.

[Link] an element is less than the root value,it is added into the left subtree as a leaf node.

[Link] an element is greater than the root value, it is added into the right subtree as a leaf node.

[Link] final leaf nodes of the tree point to NULL values as their child nodes.

[Link]
EXAMPLE:
The process of inserting a node into BST using an example.

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.

. Suppose we have to find node 20 from the below tree.

Step1:

Step2:

Step3:
Algorithm to search an element in Binary search tree
1. Search (root, item)
2. Step 1 - if (item = root → data) or (root = NULL)
3. return root
4. else if (item < root → data)
5. return Search(root → left, item)
6. else
7. return Search(root → right, item)
8. END if
9. Step 2 - END

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

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 inorder successor of the node to be deleted.


o After that, replace that node with the inorder 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 inorder successor is required when the right child of the node is not empty. We can
obtain the inorder 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 inorder successor. Now, node
45 will be at the leaf of the tree so that it can be deleted easily.
The complexity of the Binary Search tree
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 Worst case
complexity time time
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).

TREE TRAVERSAL

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
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.

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

Algorithm
Until all nodes are traversed −

Step 1 − Recursively traverse left subtree.


Step 2 − Visit root node.
Step 3 − Recursively traverse right subtree.

Logic:

void inorder_traversal(struct node* root){


if(root != NULL) {
inorder_traversal(root->leftChild);
printf("%d ",root->data);
inorder_traversal(root->rightChild);
}
}

Pre-order Traversal
In this traversal method, the root node is visited first, then the left subtree
and finally the right subtree.

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

Algorithm
Until all nodes are traversed −
Step 1 − Visit root node.
Step 2 − Recursively traverse left subtree.
Step 3 − Recursively traverse right subtree.

Example
Following are the implementations of this operation in various programming
languages –

Logic:

void pre_order_traversal(struct node* root){


if(root != NULL) {
printf("%d ",root->data);
pre_order_traversal(root->leftChild);
pre_order_traversal(root->rightChild);
}
}
}

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
Following are the implementations of this operation in various programming languages −

void post_order_traversal(struct node* root){


if(root != NULL) {
post_order_traversal(root->leftChild);
post_order_traversal(root->rightChild);
printf("%d ", root->data);
}
}
}

5.13 Write the program to implement Binary Search Tree operations.


#include <stdio.h>
#include <stdlib.h>

struct node {
int data;
struct node *right_child;
struct node *left_child;
};

struct node* new_node(int x){


struct node *temp;
temp = malloc(sizeof(struct node));
temp->data = x;
temp->left_child = NULL;
temp->right_child = NULL;

return temp;
}

struct node* search(struct node * root, int x){


if (root == NULL || root->data == x)
return root;
else if (x > root->data)
return search(root->right_child, x);
else
return search(root->left_child, x);
}

struct node* insert(struct node * root, int x){


if (root == NULL)
return new_node(x);
else if (x > root->data)
root->right_child = insert(root->right_child, x);
else
root -> left_child = insert(root->left_child, x);
return root;
}
struct node* find_minimum(struct node * root) {
if (root == NULL)
return NULL;
else if (root->left_child != NULL)
return find_minimum(root->left_child);
return root;
}

struct node* delete(struct node * root, int x) {

if (root == NULL)
return NULL;
if (x > root->data)
root->right_child = delete(root->right_child, x);
else if (x < root->data)
root->left_child = delete(root->left_child, x);
else {
if (root->left_child == NULL && root->right_child == NULL){
free(root);
return NULL;
}
else if (root->left_child == NULL || root->right_child == NULL){
struct node *temp;
if (root->left_child == NULL)
temp = root->right_child;
else
temp = root->left_child;
free(root);
return temp;
}
else {
struct node *temp = find_minimum(root->right_child);
root->data = temp->data;
root->right_child = delete(root->right_child, temp->data);
}
}
return root;
}

void inorder(struct node *root){


if (root != NULL)
{
inorder(root->left_child);
printf(" %d ", root->data);
inorder(root->right_child);
}
}

void preorder(struct node *root){


if (root != NULL)
{
printf(" %d ", root->data);
preorder(root->left_child);
preorder(root->right_child);
}
}
void postorder(struct node *root){
if (root != NULL)
{
postorder(root->left_child);
postorder(root->right_child);
printf(" %d ", root->data);

}
}

int main() {
struct node *root;
root = new_node(20);
clrscr();
insert(root, 5);
insert(root, 1);
insert(root, 15);
insert(root, 9);
insert(root, 7);
insert(root, 12);
insert(root, 30);
insert(root, 25);
insert(root, 40);
insert(root, 45);
insert(root, 42);

printf(“\n Inorder before deletion \n”);


inorder(root);
printf(“\n Preorder before deletion \n”);
preorder(root);
printf(“\n Postorder before deletion \n”);
postorder(root);

root = delete(root, 1);

root = delete(root, 40);

root = delete(root, 45);

root = delete(root, 9);


printf(“\n Inorder after deletion \n”);
inorder(root);
printf(“\n Preorder after deletion \n”);
preorder(root);
printf(“\n Postorder after deletion \n”);
postorder(root);
printf("\n");

return 0;
}
Output

Inorder before deletion


1 5 7 9 12 15 20 25 30 40 42 45
Preorder before deletion
20 5 1 15 9 7 12 30 25 40 45 42
Postorder before deletion
1 7 12 9 15 5 2542 45 40 30 20
Inorder after deletion
5 7 12 15 20 25 30 42
Preorder after deletion
20 5 15 12 7 30 25 42
Postorder after deletion
7 12 15 5 25 42 30 20
5.14 List the Applications of trees
Other Applications of Tree Data Structure:
1. Store hierarchical data, like folder structure, organization structure, XML/HTML data.
2. Binary Search Tree is a tree that allows fast search, insert, delete on a sorted data. It
also allows finding closest item
3. Heap is a tree data structure which is implemented using arrays and used to implement
priority queues.
4. In XML parser.
5. Machine learning algorithm.
6. For indexing in database.
7. In Computer Graphics.
8. To evaluate an expression.
9. In chess game to store defense moves of player.
10. Tree data structures are used to organize and manage files and directories in a file system.
Each file and directory is represented as a node in the tree, with parent-child relationships
indicating the hierarchical structure of the file system.
11. Tree data structures are often used in parsing, such as in compilers and interpreters, to
represent the structure of a program or a document.
12. Tree data structures, such as binary search trees, are commonly used to implement efficient
searching and sorting algorithms.
13. As a workflow for compositing digital images for visual effects.
14. Decision trees.
15. Organization chart of a large organization.
16. IN server like DNS (Domain Name Server)
17. In java virtual machine.
18. Graphics and UI design
19. Tree data structures are commonly used in decision-making algorithms in artificial
intelligence, such as game-playing algorithms, expert systems, and decision trees.
20. Tree data structures can be used to represent the topology of a network and to calculate
routing tables for efficient data transmission.
21. B-Tree and B+ Tree : They are used to implement indexing in databases.
22. Syntax Tree: Scanning, parsing , generation of code and evaluation of arithmetic
expressions in Compiler design.
23. Trie : Used to implement dictionaries with prefix lookup.
24. Suffix Tree : For quick pattern searching in a fixed text.
25. Spanning Trees and shortest path trees are used in routers and bridges respectively in
computer networks

You might also like