0% found this document useful (0 votes)
17 views

Unit-03

Stack

Uploaded by

Dr. S.K. Sajan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Unit-03

Stack

Uploaded by

Dr. S.K. Sajan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

UNIT-3

Tree ADT-tree traversals-Binary Tree ADT-expression trees-applications of trees-


binary searchtree ADT- Threaded Binary Trees-AVL Trees- B-Tree- B+ Tree –
Heap-Applications of heap.

BINARY TREE TRAVERSALS


Compared to linear data structures like linked lists and one dimensional array, which have only
one logical means of traversal, tree structures can be traversed in many different ways. Starting
at the root of a binary tree, there are three main steps that can be performed and the order in
which they are performed defines the traversal type. These steps (in no particular order) are:
performing an action on the current node (referred to as "visiting" the node), traversing to the left
child node, and traversing to the right child node. Thus the process is most easily described
through recursion. A binary tree traversal requires that each node of the tree be processed once
and only once in a predetermined sequence.

The two general approaches to the traversal sequence are,


1. Depth first traversal
2. Breadth first traversal
Breadth-First Traversal
In a breadth-first traversal, the processing proceeds horizontally form the root to all its children,
then to its children’s children, and so forth until all nodes have been processed. In other words, in
breadth traversal, each level is completely processed before the next level is started.
Depth-First Traversal
In depth first traversal, the processing proceeds along a path from the root through one child to
the most distant descendent of that first child before processing a second child. In other words, in
the depth first traversal, all the descendants of a child are processed before going to the next
child.

There are basically three ways of binary tree traversals.


1. Inorder --- (left child,root,right child)
2. Preorder --- (root,left child,right child)
3. Postorder --- (left child,right child,root)

Inorder --- B A C
Preorder --- A B C
Postorder --- B C A
Inorder Traversal
Steps :
 Traverse left subtree in inorder
 Process root node
 Traverse right subtree in inorder

Algorithm
Algorithm inorder traversal (BinTree T)
Begin
If ( not empty (T) ) then
Begin
Inorder_traversal ( left subtree ( T ) )
Print ( info ( T ) ) / * process node */
Inorder_traversal ( right subtree ( T ) )
End
End

Preorder Traversal
Steps :
 Process root node
 Traverse left subtree in preorder
 Traverse right subtree in preorder
Algorithm
Algorithm inorder traversal (BinTree T)
Begin
If ( not empty (T) ) then
Begin
Print ( info ( T ) ) / * process node */
Preorder_traversal ( left subtree ( T ) )
Preorder_traversal ( right subtree ( T ) )
End
End

Postorder Traversal
Steps :
 Traverse left subtree in postorder
 Traverse right subtree in postorder
 process root node

Algorithm
Algorithm postorder traversal (BinTree T)
Begin
If ( not empty (T) ) then
Begin
Postorder_traversal ( left subtree ( T ) )
Postorder_traversal ( right subtree( T))
Print ( Info ( T ) ) / * process node */
End
End
Example: 1
Find the Preorder, Inorder and Postorder traversal of the following Tree

Preorder traversal sequence: F, B, A, D, C, E, G, I, H (root, left, right)


Inorder traversal sequence: A, B, C, D, E, F, G, H, I (left, root, right)
Postorder traversal sequence: A, C, E, D, B, H, I, G, F (left, right, root)

Example: 2
A Binary Tree Has 8 Nodes. The Inorder And Postorder Traversal Of The Tree Are Given
Below. Draw The Tree And Find Preorder.
APPLICATIONS
1. Some applications of preorder traversal are the evaluation of expressions in prefix
notation and the processing of abstract syntax trees by compilers.
2. Binary search trees (a special type of BT) use inorder traversal to print all of their
data in alphanumeric order.
3. A popular application for the use of postorder traversal is the evaluating of
expressions in postfix notation.

Expression Tree

The expression tree is a binary tree in which each internal node corresponds to the
operator and each leaf node corresponds to the operand so for example expression tree for
3 + ((5+9)*2) would be:

Construction of Expression Tree:


Now For constructing an expression tree we use a stack. We loop through input expression and
do the following for every character.

1. If a character is an operand push that into the stack


2. If a character is an operator pop two values from the stack make them its child and push the
current node again.
In the end, the only element of the stack will be the root of an expression tree.
Evaluation of Expression Tree
Given a simple expression tree, consisting of basic binary operators i.e., +, –, * and / and some
integers, evaluate the expression tree.

Examples: 1
Input: Root node of the below tree

Output: 100

Examples: 2
Input: Root node of the below tree

Output: 110
As an example, suppose the input is:
ab+cde+**
The first two symbols are operands, so we create one-node trees and push pointers to
them onto a stack.*

*For convenience, we will have the stack grow from left to right in the diagrams.

Next, a '+' is read, so two pointers to trees are popped, a new tree is formed, and a pointer to it is
pushed onto the stack.*

Next, c, d, and e are read, and for each a one-node tree is created and a pointer to the
corresponding tree is pushed onto the stack.

Now a '+' is read, so two trees are merged.


Continuing, a '*' is read, so we pop two tree pointers and form a new tree with a '*' as
root.
Finally, the last symbol is read, two trees are merged, and a pointer to the final tree is left on the
stack.

Applications of Tree:
 File Systems: The file system of a computer is often represented as a tree. Each folder or
directory is a node in the tree, and files are the leaves.
 XML Parsing: Trees are used to parse and process XML documents. An XML document
can be thought of as a tree, with elements as nodes and attributes as properties of the nodes.
 Database Indexing: Many databases use trees to index their data. The B-tree and its
variations are commonly used for this purpose.
 Compiler Design: The syntax of programming languages is often defined using a tree
structure called a parse tree. This is used by compilers to understand the structure of the
code and generate machine code from it.
 Artificial Intelligence: Decision trees are often used in artificial intelligence to make
decisions based on a series of criteria.

Real-Time Applications of Tree :


 Databases use tree data structure for indexing.
 Tree data structure is used in file directory management.
 DNS uses tree data structure.
 Trees are used in several games like moves in chess.
 Decision-based algorithms in machine learning uses tree algorithms.
Advantages of Tree:
 Efficient searching: Trees are particularly efficient for searching and retrieving data. The
time complexity of searching in a tree is typically O(log n), which means that it is very fast
even for very large data sets.
 Flexible size: Trees can grow or shrink dynamically depending on the number of nodes
that are added or removed. This makes them particularly useful for applications where the
data size may change over time.
 Easy to traverse: Traversing a tree is a simple operation, and it can be done in several
different ways depending on the requirements of the application. This makes it easy to
retrieve and process data from a tree structure.
 Easy to maintain: Trees are easy to maintain because they enforce a strict hierarchy and
relationship between nodes. This makes it easy to add, remove, or modify nodes without
affecting the rest of the tree structure.
 Natural organization: Trees have a natural hierarchical organization that can be used to
represent many types of relationships. This makes them particularly useful for representing
things like file systems, organizational structures, and taxonomies.
 Fast insertion and deletion: Inserting and deleting nodes in a tree can be done in O(log n)
time, which means that it is very fast even for very large trees.
Disadvantages of Tree:
 Memory overhead: Trees can require a significant amount of memory to store, especially
if they are very large. This can be a problem for applications that have limited memory
resources.
 Imbalanced trees: If a tree is not balanced, it can result in uneven search times. This can
be a problem in applications where speed is critical.
 Complexity: Trees can be complex data structures, and they can be difficult to understand
and implement correctly. This can be a problem for developers who are not familiar with
them.
 Limited flexibility: While trees are flexible in terms of size and structure, they are not as
flexible as other data structures like hash tables. This can be a problem in applications
where the data size may change frequently.
 Inefficient for certain operations: While trees are very efficient for searching and
retrieving data, they are not as efficient for other operations like sorting or grouping. For
these types of operations, other data structures may be more appropriate.
BINARY SEARCH TREE
Binary search tree (BST) is a node-based binary tree data structure which has the following
properties:
 The left sub-tree of a node contains only nodes with keys less than the node's key.
 The right sub-tree of a node contains only nodes with keys greater than the node's key.
 Both the left and right sub-trees must also be binary search trees.

Binary Search Tree


 The Values in the left subtree must be smaller than the keyvalue to be inserted.
 The Values in the right subtree must be larger than the keyvalue to be inserted.

Take the 1st element 2 and compare with 4. 2<4

1 5

7
OPERATIONS
Operations on a binary tree require comparisons between nodes. These comparisons are
made with calls to a comparator, which is a subroutine that computes the total order
(linear order) on any two values. This comparator can be explicitly or implicitly defined,
depending on the language in which the BST is implemented.

The following are the operations that are being done in Binary Tree
 Searching.
 Sorting.
 Deletion.
 Insertion.

Find
This operation generally requires returning a pointer to the node in tree T that has
key x, or NULL if there is no such node. The structure of the tree makes this simple. If T
is, then we can just return. Otherwise, if the key stored at T is x, we can return T.
Otherwise, we make a recursive call on a subtree of T, either left or right, depending on
the relationship of x to the key stored in T.

Insert
The insertion routine is conceptually simple. To insert x into tree T, proceed down
the tree as you would with a find. If x is found, do nothing (or "update" something).
Otherwise, insert x at the last spot on the path traversed. Figure below shows what
happens. To insert 5, we traverse the tree as though a find were occurring. At the node
with key 4, we need to go right, but there is no subtree, so 5 is not in the tree, and this is
the correct spot.
Duplicates can be handled by keeping an extra field in the node record indicating
the frequency of occurrence. This adds some extra space to the entire tree, but is better
than putting duplicates in the tree (which tends to make the tree very deep). Of course
this strategy does not work if the key is only part of a larger record. If that is the case,
then we can keep all of the records that have the same key in an auxiliary data structure,
such as a list or another search tree.
EXAMPLE Insert node 5 in given tree
Delete
As is common with many data structures, the hardest operation is deletion. Once we have
found the node to be deleted, we need to consider several possibilities. If the node is a
leaf, it can be deleted immediately. If the node has one child, the node can be deleted
after its parent adjusts a pointer to bypass the node (we will draw the pointer directions
explicitly for clarity).. Notice that the deleted node is now unreferenced and can be
disposed of only if a pointer to it has been saved. The complicated case deals with a node
with two children. The general strategy is to replace the key of this node with the smallest
key of the right subtree (which is easily found) and recursively delete that node (which is
now empty). Because the smallest node in the right subtree cannot have a left child, the
second delete is an easy one. To delete an element, consider the following three
possibilities :
Case 1: Node to be deleted is a leaf node.
Case 2: Node with only one child.
Case 3: Node with two children.

Case 1: Node with no children | Leaf node :


1. Search the parent of the leaf node and make the link to the leaf node as NULL.
2. Release the memory of the deleted node.

Case 2: Node with only one child :


1. Search the parent of the node to be deleted.
2. Assign the link of the parent node to the child of the node to be deleted.
3. Release the memory for the deleted node.
Case 3: Node with two children :
It is difficult to delete a node which has two children. So, a general strategy has to
be followed.
1. Replace the data of the node to be deleted with either the largest element from the
left subtree or the smallest element from the right subtree.

You might also like