Lesson 06s SDD
Lesson 06s SDD
LESSON 06 – Trees
Introduction
We have studied stack, queues and lists which are special form of sequences. Sequences are
classified as linear data structures. The linear data structure is one each component has a
unique predecessor component and a unique successor component. Trees and graphs in
contrast to sequences are nonlinear data structure, since they contain component which may
have more than one successor and more than one predecessor. During this lesson we learn
about trees and how to implement tree structure in Java.
Learning outcome
After completing this lesson, you would be able to define trees and different types of operations
can be performed over them. Thus you should be able to,
Define a binary tree
Describe trees operations
Compare and contrast different types of trees
Define heaps
Level 2
Level 3
1
Trees
ITE 2142 – Data Structures & Algorithms Week 06
6.1.4 Siblings
Children of same parent are said to be siblings. For example B, C and D are siblings.
6.1.5 Ancestors
Ancestors of a node are the nodes above the path from the root to that node. For example ancestors of
F are D and A.
2
Trees
ITE 2142 – Data Structures & Algorithms Week 06
6.1.9 Forest
A forest is the set of disjoint trees. The notion of forest is very close to that of a tree because
if we remove the root of a tree we get the forest. For example if we remove the node A which
is the root node we get three forests.
Node
edge
3
Trees
ITE 2142 – Data Structures & Algorithms Week 06
Advantages of binary array combine advantages of two other structures: an ordered array
and a linked list. You can search a tree quickly as you can in an ordered array, and you can
also insert and delete items quickly, as you can with a linked list.
In computer programs, nodes often represent such entities as people, car parts, airline
reservations, and so on; in other works, the typical items we store in any kind of data
structure. In an OOP language such Java, these real-world entities are represented by
objects. The lines (edges) between the nodes represent the way the nodes are related.
Roughly speaking, the lines represent convenience: it’s easy for a program to get from one
node to another if there is a line connecting them. In fact, the only way to get from a node to
node is to follow a path along the lines. Generally you are restricted to going in one direction
along edges: i.e. from the root downward.
class Node
{
public int iData; // data item (key)
public double dData; // data item
public Node leftChild; // this node's left child public
Node rightChild; // this node's rightchild
4
Trees
ITE 2142 – Data Structures & Algorithms Week 06
We will also need a class from which to instantiate the tree itself; the object that holds all
the nodes. We will call this class Tree. It has only one field: a node variable that holds the
root. It doesn’t need fields for the other nodes because they are all accessed from the root.
It has number of methods: some for finding, inserting deleting nodes, several for different
kinds of traverse and one to display the tree. Here’s a skeleton of the tree class.
class Tree
{
private Node root; // first node of tree
Next we will look at individual tree operations: finding a node, inserting a node, traversing
the tree and deleting a node.
Consider the following binary tree and suppose that you want to find the node representing
item with key value 57. The finding process can be depicted as follows in Figure 6.1.
7
Trees
ITE 2142 – Data Structures & Algorithms Week 06
if(root==null) // no node in
root root = newNode;
else // root occupied
{
Node current = root; // start atroot
Node parent;
Consider the following tree. Suppose that you want to insert an element 100. First
we find the appropriate node, which will be the parent of the new node. Following
the find method, we can find parent of new node as 92. So we can insert new node
8
Trees
ITE 2142 – Data Structures & Algorithms Week 06
9
Trees
ITE 2142 – Data Structures & Algorithms Week 06
L R
In this figure, N denotes a node. L and R denotes left and right sub trees of the node N,
now it’s ordering can be classified as,
6.3.1 Pre-order
That’s visit the node before each of left sub tree. i.e. root left right
10
Trees
ITE 2142 – Data Structures & Algorithms Week 06
6.3.2 In-order
That’s visit node between visiting it’s subtrees. i.e. left root right
For example consider the following tree.
11
Trees
ITE 2142 – Data Structures & Algorithms Week 06
6.3.3 Post-order
That’s visit the node after visiting it’s sub trees. i. e. left right root
For example consider the following tree.
12
Trees
ITE 2142 – Data Structures & Algorithms Week 06
Note: Obviously in-order traversal of a binary search tree is appropriate for dealing with its
value in sorted order.
Activity 6.1
Consider the following tree. What would be the output value if we traverse through the tree
using in -order traversal?
A binary heap is a complete binary tree which satisfies the heap ordering property. The ordering
can be one of two types:
the min-heap property: the value of each node is greater than or equal to the value of its
parent, with the minimum-value element at the root.
the max-heap property: the value of each node is less than or equal to the value of its parent,
with the maximum-value element at the root.
13
Trees
ITE 2142 – Data Structures & Algorithms Week 06
Throughout this chapter the word "heap" will always refer to a min-heap. These types create two
different heap tree structures as shown in the following Figure 6.3.
In a heap the highest (or lowest) priority element is always stored at the root, hence the name "heap".
A heap is not a sorted structure and can be regarded as partially ordered. As you see from the picture,
there is no particular relationship among nodes on any given level, even among the siblings.
Since a heap is a complete binary tree, it has a smallest possible height - a heap with N nodes always
has O(log N) height. A heap is useful data structure when you need to remove the object with the highest
(or lowest) priority. A common use of a heap is to implement a priority queue.
A Min Heap is a Complete Binary Tree. A Min heap is typically represented as an array. The root
element will be at Arr[0]. For any ith node, i.e., Arr[i]:
14
Trees
ITE 2142 – Data Structures & Algorithms Week 06
2. extractMin(): Removes the minimum element from MinHeap. Time Complexity of this
Operation is O(Log n) as this operation needs to maintain the heap property (by calling
heapify()) after removing root.
3. insert(): Inserting a new key takes O(Log n) time. We add a new key at the end of the tree. If
new key is larger than its parent, then we don’t need to do anything. Otherwise, we need to
traverse up to fix the violated heap property.
// Function to return the position of the parent for the node currently
// at pos
15
Trees
ITE 2142 – Data Structures & Algorithms Week 06
16
Trees
ITE 2142 – Data Structures & Algorithms Week 06
17
Trees
ITE 2142 – Data Structures & Algorithms Week 06
// Driver code
public static void main(String[] arg)
{
System.out.println("The Min Heap is ");
MinHeap minHeap = new MinHeap(15);
minHeap.insert(5);
minHeap.insert(3);
minHeap.insert(17);
minHeap.insert(10);
minHeap.insert(84);
minHeap.insert(19);
minHeap.insert(6);
minHeap.insert(22);
minHeap.insert(9);
minHeap.minHeap();
minHeap.print();
System.out.println("The Min val is " + minHeap.remove());
}
}
A Max Heap is a Complete Binary Tree. A Max heap is typically represented as an array. The root
element will be at Arr[0]. Below table shows indexes of other nodes for the ith node, i.e., Arr[i]:
Arr[(i-1)/2] Returns the parent node.
Arr[(2*i)+1] Returns the left child node.
Arr[(2*i)+2] Returns the right child node.
2) extractMax(): Removes the maximum element from MaxHeap. Time Complexity of this Operation
is O(Log n) as this operation needs to maintain the heap property (by calling heapify()) after removing
root.
4) insert(): Inserting a new key takes O(Log n) time. We add a new key at the end of the tree. If new
18
Trees
ITE 2142 – Data Structures & Algorithms Week 06
key is smaller than its parent, then we don’t need to do anything. Otherwise, we need to traverse up to
fix the violated heap property.
// Constructor to initialize an
// empty max heap with given maximum
// capacity.
public MaxHeap(int maxsize)
{
this.maxsize = maxsize;
this.size = 0;
Heap = new int[this.maxsize + 1];
Heap[0] = Integer.MAX_VALUE;
}
19
Trees
ITE 2142 – Data Structures & Algorithms Week 06
20
Trees
ITE 2142 – Data Structures & Algorithms Week 06
// A recursive function to max heapify the given subtree. This function assumes that the left and
// right subtrees are already heapified, we only need to fix the root.
private void maxHeapify(int pos)
{
if (isLeaf(pos))
return;
if (Heap[pos] < Heap[leftChild(pos)] ||
Heap[pos] < Heap[rightChild(pos)]) {
Summary
In this lesson you have learnt about Trees. You learnt how to traverse through a tree, how to
implement trees and perform tree operations in Java programming language. You learnt about
different types of tree data structure including Heap trees. Next lesson we will learn about
graph data structure.
23
Trees