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

WEEK 5

COURSE CODE: IT 221


TITLE: DATA STRUCTURES AND ALGORITHMS
TARGET POPULATION: SECOND YEAR STUDENTS AND IRREGULAR STUDENTS
INSTRUCTOR: CEDIE E. GABRIEL

OVERVIEW
Is not the main objective to present you with the theorems and proofs on data structures
and algorithms. We have followed a pattern of improving the problem solutions with
different complexities (for each problem, you will find multiple solutions with different,
and reduced, complexities). Basically, it’s an enumeration of possible solutions. With
this approach, even if you get a new question, it will show you a way to think about the
possible solutions. You will find these topics useful for interview preparation, competitive
exams preparation, and campus interview preparations.

LEARNING OBJECTIVES
1. Describe the Tree ADT;
2. Design algorithms that operate on Tree;
3. Compare the efficiencies of algorithms that implement list operations using binary
trees;
4. Discuss some problems and solutions when implementing binary tree in ;

INTRODUCTION TO THE LEARNERS


An appropriate data structure must be chosen to represent the data and the
relationships among data. A linked structure results when the data are made to point to
other data to show relationship. The linked list is a linked structure for data that are
sequenced one after another. It is an alternative to an array to store items sequentially.
BINARY TREE

5.1 WHAT IS A TREE?


A tree is a data structure similar to a linked list but instead of each node pointing simply
to the next node in a linear fashion, each node points to a number of nodes. Tree is an
example of a non-linear data structure. A tree structure is a way of representing the
hierarchical nature of a structure in a graphical form.
In trees ADT (Abstract Data Type), the order of the elements is not important. If we
need ordering information, linear data structures like linked lists, stacks, queues, etc.
can be used.

 The root of a tree is the node with no parents. There can be at most one root
node in a tree (node A in the above example).
 An edge refers to the link from parent to child (all links in the figure).
 A node with no children is called leaf node (E,J,K,H and I).
 Children of same parent are called siblings (B,C,D are siblings of A, and E,F are
the
 siblings of B).
 A node p is an ancestor of node q if there exists a path from root to q and p
appears on the path. The node q is called a descendant of p. For example, A,C
and G are the ancestors of if.
 The set of all nodes at a given depth is called the level of the tree (B, C and D
are the same level). The root node is at level zero.

Binary Trees
A tree is called binary tree if each node has zero child, one child or two children. Empty
tree is also a valid binary tree. We can visualize a binary tree as consisting of a root and
two disjoint binary trees, called the left and right subtrees of the root.
Generic Binary Tree

Types of Binary Trees


Strict Binary Tree: A binary tree is called strict binary tree if each node has exactly two
children or no children.
Full Binary Tree: A binary tree is called full binary tree if each node has exactly two
children and all leaf nodes are at the same level.

Complete Binary Tree: Before defining the complete binary tree, let us assume that the
height of the binary tree is h. In complete binary trees, if we give numbering for the
nodes by starting at the root (let us say the root node has 1) then we get a complete
sequence from 1 to the number of nodes in the tree. While traversing we should give
numbering for NULL pointers also. A binary tree is called complete binary tree if all leaf
nodes are at height h or h – 1 and also without any missing number in the sequence.

Properties of Binary Trees


For the following properties, let us assume that the height of the tree is h. Also, assume
that root node is at height zero
From the diagram we can infer the following properties:

 The number of nodes n in a full binary tree is 2 h+1 – 1. Since, there are h levels
we need to add all nodes at each level [2 0 + 2 1+ 2 2 + ··· + 2 h = 2 h+1 – 1].
 The number of nodes n in a complete binary tree is between 2 h (minimum) and
2 h+1 – 1 (maximum). For more information on this, refer to Priority Queues
chapter. • The number of leaf nodes in a full binary tree is 2 h . • The number of
NULL links (wasted pointers) in a complete binary tree of n nodes is n + 1.

Structure of Binary Trees


Now let us define structure of the binary tree. For simplicity, assume that the data of
the nodes are integers. One way to represent a node (which contains data) is to
have two links which point to left and right children along with data fields as shown

below:
Note: In trees, the default flow is from parent to children and it is not mandatory to show
directed branches. For our discussion, we assume both the representations shown
below are the same.
Operations on Binary Trees Basic Operations
 Inserting an element into a tree
 Deleting an element from a tree
 Searching for an element
 Traversing the tree Auxiliary Operations
 Finding the size of the tree
 Finding the height of the tree
 Finding the level which has maximum sum
 Finding the least common ancestor (LCA) for a given pair of nodes, and many
more.

Applications of Binary Trees


Following are the some of the applications where binary trees play an important role:
 Expression trees are used in compilers.
 Huffman coding trees that are used in data compression algorithms.
 Binary Search Tree (BST), which supports search, insertion and deletion on a
collection of items in O(logn) (average).
 Priority Queue (PQ), which supports search and deletion of minimum (or
maximum) on a collection of items in logarithmic time (in worst case).
Binary Tree Traversals
In order to process trees, we need a mechanism for traversing them, and that forms the
subject of this section. The process of visiting all nodes of a tree is called tree traversal.
Each node is processed only once but it may be visited more than once. As we have
already seen in linear data structures (like linked lists, stacks, queues, etc.), the
elements are visited in sequential order. But, in tree structures there are many different
ways.
Tree traversal is like searching the tree, except that in traversal the goal is to move
through the tree in a particular order. In addition, all nodes are processed in the
traversal but searching stops when the required node is found.
Classifying the Traversals
The sequence in which these entities (nodes) are processed defines a particular
traversal method. The classification is based on the order in which current node is
processed. That means, if we are classifying based on current node (D) and if D comes
in the middle then it does not matter whether L is on left side of D or R is on left side of
D.
Similarly, it does not matter whether L is on right side of D or R is on right side of D. Due
to this, the total 6 possibilities are reduced to 3 and these are:
 Preorder (DLR) Traversal
 Inorder (LDR) Traversal
 Postorder (LRD) Traversal
PreOrder Traversal
In preorder traversal, each node is processed before (pre) either of its subtrees. This is
the simplest traversal to understand. However, even though each node is processed
before the subtrees, it still requires that some information must be maintained while
moving down the tree. In the example above, 1 is processed first, then the left subtree,
and this is followed by the right subtree.
Therefore, processing must return to the right subtree after finishing the processing of
the left subtree. To move to the right subtree after processing the left subtree, we must
maintain the root information. The obvious ADT for such information is a stack. Because
of its LIFO structure, it is possible to get the information about the right subtrees back in
the reverse order.

Preorder traversal is defined as follows:


 Visit the root.
 Traverse the left subtree in Preorder.
 Traverse the right subtree in Preorder.
The nodes of tree would be visited in the order: 1 2 4 5 3 6 7
Non-Recursive Preorder Traversal
In the recursive version, a stack is required as we need to remember the current node
so that after completing the left subtree we can go to the right subtree. To simulate the
same, first we process the current node and before going to the left subtree, we store
the current node on stack. After completing the left subtree processing, pop the element
and go to its right subtree. Continue this process until stack is nonempty.

InOrder Traversal

In Inorder Traversal the root is visited between the subtrees. Inorder traversal is defined
as follows:
 Traverse the left subtree in Inorder.
 Visit the root.
 raverse the right subtree in Inorder.
The nodes of tree would be visited in the order: 4 2 5 1 6 3 7

Non-Recursive Inorder Traversal


The Non-recursive version of Inorder traversal is similar to Preorder. The only change
is, instead of processing the node before going to left subtree, process it after popping
(which is indicated after completion of left subtree processing).

PostOrder Traversal
In postorder traversal, the root is visited after both subtrees. Postorder traversal is
defined as follows:
 Traverse the left subtree in Postorder.
 Traverse the right subtree in Postorder.
 Visit the root.
The nodes of the tree would be visited in the order: 4 5 2 6 7 3 1

Non-Recursive Postorder Traversal


In preorder and inorder traversals, after popping the stack element we do not need to
visit the same vertex again. But in postorder traversal, each node is visited twice. That
means, after processing the left subtree we will visit the current node and after
processing the right subtree we will visit the same current node. But we should be
processing the node during the second visit. Here the problem is how to differentiate
whether we are returning from the left subtree or the right subtree.
We use a previous variable to keep track of the earlier traversed node. Let’s assume
current is the current node that is on top of the stack. When previous is current’s parent,
we are traversing down the tree. In this case, we try to traverse to current’s left child if
available (i.e., push left child to the stack). If it is not available, we look at current’s right
child. If both left and right child do not exist (ie, current is a leaf node), we print current’s
value and pop it off the stack.
If prev is current’s left child, we are traversing up the tree from the left. We look at
current’s right child. If it is available, then traverse down the right child (i.e., push right
child to the stack); otherwise print current’s value and pop it off the stack. If previous is
current’s right child, we are traversing up the tree from the right. In this case, we print
current’s value and pop it off the stack.
Level Order Traversal
Level order traversal is defined as follows:
 Visit the root.
 While traversing level (, keep all the elements at level ( + 1 in queue.
 Go to the next level and visit all the nodes at that level.
 Repeat this until all levels are completed.
The nodes of the tree are visited in the order: 1 2 3 4 5 6 7

You might also like