SlideShare a Scribd company logo
1 of 18
© Oxford University Press 2011. All rights reserved.
Data Structures Using CData Structures Using C
Reema TharejaReema Thareja, Assistant Professor, Institute of
Information Technology and Management,
New Delhi
© Oxford University Press 2011. All rights reserved.
CHAPTER 10
TREES
© Oxford University Press 2011. All rights reserved.
BINARY TREES
• A binary tree is a data structure which is defined as a collection of
elements called nodes. Every node contains a "left" pointer, a "right"
pointer, and a data element. Every binary tree has a root element pointed
by a "root" pointer. The root element is the topmost node in the tree. If
root = NULL, then it means the tree is empty.
• If the root node R is not NULL, then the two trees T1 and T2 are called the
left and right subtrees of R. if T1 is non-empty, then T1 is said to be the
left successor of R. likewise, if T2 is non-empty then, it is called the right
successor of R.
8
1
32
4
5 6 7
1
2
1
0
1
1
ROOT NODE
T2T1
9
In a binary tree every node has 0, 1 or at the
most 2 successors. A node that has no
successors or 0 successors is called the leaf
node or the terminal node.
© Oxford University Press 2011. All rights reserved.
KEY TERMS
• Sibling: If N is any node in T that has left successor S1 and right successor
S2, then N is called the parent of S1 and S2. Correspondingly, S1 and S2
are called the left child and the right child of N. Also, S1 and S2 are said to
be siblings. Every node other than the root node has a parent. In other
words, all nodes that are at the same level and share the same parent are
called siblings (brothers).
Level number: Every node in the binary tree is assigned a level number. The
root node is defined to be at level 0. The left and right child of the root node
has a level number 1. Similarly, every node is at one level higher than its
parents. So all child nodes are defined to have level number as parent’s
level number + 1.
• Degree: Degree of a node is equal to the number of children that a node
has. The degree of a leaf node is zero.
In-degree of a node is the number of edges arriving at that node. The root
node is the only node that has an in-degree equal to zero. Similarly,
Out-degree of a node is the number of edges leaving that node.
Leaf node: A leaf node has no children.
© Oxford University Press 2011. All rights reserved.
KEY TERMS contd.
Similar binary trees: Given two binary trees T and T’ are said to be similar if both
of these trees have the same structure.
A
CB
D
E
F
HG
I
J
TREE T’
TREE T”
Copies of binary trees: Two binary trees T and T’ are said to be copies if they have
similar structure and same contents at the corresponding nodes.
A
CB
D E
A
CB
D
E
TREE T’
TREE T”
© Oxford University Press 2011. All rights reserved.
KEY TERMS contd.
• Directed edge: Line drawn from a node N to any of its successor is called a
directed edge. A binary tree of n nodes have exactly n – 1 edges (because, every
node except the root node is connected to its parent via an edge).
• Path: A sequence of consecutive edges is called a path.
• Depth: The depth of a node N is given as the length of the path from the root R to
the node N. The depth of the root node is zero. The height/depth of a tree is
defined as the length of the path from the root node to the deepest node in the
tree.
A tree with only a root node has a height of zero. A binary tree of height h, has at
least h nodes and at most 2h – 1
nodes. This is because every level will have at least
one node and can have at most 2 nodes. So, if every level has two nodes then a
tree with height h will have at the most 2h – 1
nodes as at level 0, there is only one
element called the root. The height of a binary tree with n nodes is at least n and at
most log2(n+1)
• Ancestor and descendant nodes: Ancestors of a node are all the nodes along the
path from the root to that node. Similarly, descendants of a node are all the nodes
along the path from that node to the leaf node.
• Binary trees are commonly used to implement binary search trees, expression
trees, tournament trees and binary heaps.
© Oxford University Press 2011. All rights reserved.
Complete Binary Trees
• A complete binary tree is a binary tree which satisfies two properties. First, in a
complete binary tree every level, except possibly the last, is completely filled.
Second, all nodes appear as far left as possible
• In a complete binary tree Tn, there are exactly n nodes and level r of T can have at
most 2r
nodes.
• The formula to find the parent, left child and right child can be given as- if K is a
parent node, then its left child can be calculated as 2 * K and its right child can be
calculated as 2 * K + 1. For example, the children of node 4 are 8 (2*4) and 9 (2* 4 +
1). Similarly, the parent of the node K can be calculated as | K/2 |. Given the node 4,
its parent can be calculated as | 4/2 | = 2. The height of a tree Tn having exactly n
nodes is given as,
• Hn = | log2 n + 1 |
• This means, if a tree T has 10,00,000 nodes then its height is 21.
1
32
4
8
5 6
7
1
3
1
0
1
1
9 1
2
© Oxford University Press 2011. All rights reserved.
Extended Binary Trees
• A binary tree T is said to be an extended binary tree (or a 2-tree) if each node in
the tree has either no child or exactly two children. Figure shows how an ordinary
binary tree is converted into an extended binary tree.
• In an extended binary tree nodes that have two children are called internal nodes
and nodes that have no child or zero children are called internal nodes. In the
figure internal nodes are represented using a circle and external nodes are
represented using squares.
• To convert a binary tree into an extended tree, every empty sub-tree is replaced
by a new node. The original nodes in the tree are the internal nodes and the new
nodes added are called the external nodes.
Binary tree
Extended binary tree
© Oxford University Press 2011. All rights reserved.
Representation of Binary Trees
in Memory
• In computer’s memory, a binary tree can be maintained either using a linked
representation (as in case of a linked list) or using sequential representation
(as in case of single arrays).
Linked Representation of Binary TreesLinked Representation of Binary Trees
• In linked representation of binary tree, every node will have three parts, the
data element, a pointer to the left node and a pointer to the right node. So in
C, the binary tree is built with a node type given as below.
struct node {
struct node* left;
int data;
struct node* right;
};
1
2 3
4 5 6 7
X 8 X X 9 X X 10 X X 11 X X 12 X
© Oxford University Press 2011. All rights reserved.
Sequential Representation of
Binary Trees
• Sequential representation of trees is done using single or one
dimensional array. Though, it is the simplest technique for memory
representation but it is very inefficient as it requires a lot of memory
space. A sequential binary tree follows the rules given below:
• One dimensional array called TREE, will be used.
• The root of the tree will be stored in the first location. That is,
TREE[0] will store the data of the root element.
• The children of a node K, will be stored in location (2*K) and (2*K+1).
• The maximum size of the array TREE is given as (2d+1
-1), where d is
the depth of the tree.
• An empty tree or sub-tree is specified using NULL. If TREE[0] =
NULL, then the tree is empty.
3515
12
17 2
1
3
9
4
51
6
1
8
3
6
20
0 20
1
2 15
3 35
4 12
5 17
6 21
7 39
8
9
10 16
11 18
12
13
14 36
15 45
16
17
18
© Oxford University Press 2011. All rights reserved.
EXPRESSION TREES
• Binary trees are widely used to store algebraic expressions. For
example, consider the algebraic expression Exp given as,
• Exp = (a – b ) + ( c * d)
• This expression can be represented using a binary tree as shown in
figure
+
*-
a b c d
© Oxford University Press 2011. All rights reserved.
TOURNAMENT TREES
• In a tournament tree (also called a selection tree), each external node
represents a player and each internal node represents the winner of the
match played between the players represented by its children nodes. These
tournament trees are also called winner trees because they are being used
to record the winner at each level. We can also have a loser tree that
records the loser at each level.
a
ea
a
a
d e g
fc db e hg
© Oxford University Press 2011. All rights reserved.
TRAVERSING OF A BINARY TREE
• Traversing a binary tree is the process of visiting each node in the tree exactly
once, in a systematic way. Unlike linear data structures in which the elements
are traversed sequentially, tree is a non-linear data structure in which the
elements can be traversed in many different ways. There are different
algorithms for tree traversals. These algorithms differ in the order in which the
nodes are visited. In this section, we will read about these algorithms.
• Pre-order algorithm
To traverse a non-empty binary tree in preorder, the following operations are
performed recursively at each node. The algorithm starts with the root node of
the tree and continues by,
• Visiting the root node.
• Traversing the left subtree.
• Traversing the right subtree.
A
CB
D E
F
IH
GA, B, D, C, E, F, G, H and I
© Oxford University Press 2011. All rights reserved.
In-order algorithm
To traverse a non-empty binary tree in in-order, the following operations
are performed recursively at each node. The algorithm starts with the root
node of the tree and continues by,
• Traversing the left subtree.
• Visiting the root node.
• Traversing the right subtree.
Post-order algorithm
To traverse a non-empty binary tree in post-order, the following operations
are performed recursively at each node. The algorithm starts with the root
node of the tree and continues by,
• Traversing the left subtree.
• Traversing the right subtree.
• Visiting the root node.
A
CB
D E
F
IH
G
B, D, A, E, H, G, I, F AND C.
D, B, H, I, G, F, E, C and A.
© Oxford University Press 2011. All rights reserved.
HUFFMAN’S TREE
• Huffman coding is an entropy encoding algorithm developed by David A. Huffman
that is widely used as a lossless data compression technique. The Huffman coding
algorithm uses a variable-length code table to encode a source character where
the variable-length code table is derived in a particular way based on the
estimated probability of occurrence for each possible value of the source
character.
• The key idea behind the Huffman algorithm is that it encodes the most common
characters using shorter strings of bits than are used for less common source
characters.
• The algorithm works by creating a binary tree of nodes that are stored in a regular
array. The size of this array depends on the number of number of nodes in the
tree.
• The external path length of a binary tree is defined as the sum of all path lengths
summed over each path from the root to the external node. The internal path
length is also defined in the same manner. The internal path length of a binary tree
is defined as the sum of all path lengths summed over each path from the root to
the internal node.
© Oxford University Press 2011. All rights reserved.
• The internal path length, LI = 0 + 1 + 2 + 1 + 2 + 3 + 3 = 12
• The external path length, LE = 2 + 3 + 3 + 2 + 4 + 4 + 4 + 4 = 26
• Note that, LI + 2 * n = 12 + 2 * 7 = 12 + 14 = 26 = LE
• Hence, the formula is LI + 2n = LE, where n is the number of
internal nodes.
• Now if the tree with n external nodes is assigned a weight, then
the weighted path length, P is defined as the sum of the
weighted path lengths.
• Therefore, P = W1L1 + W2L2 + …. + WnLn,
• where, Wi and Li are the weight and path length of the external
node Ni.
The Huffman Algorithm
Step 1: Create a leaf node for each character. Add the character and its weight
or frequency of occurrence to the priority queue.
Step 2: Repeat Steps 3 to 5 while the total number of nodes in the queue is
greater than 1
Step 3: Remove two nodes that have the lowest weight (or highest priority)
Step 4: Create a new internal node by merging these two nodes as children and
with weight equal to the sum of the two nodes' weights.
Step 5: Add the newly created node to the queue.
© Oxford University Press 2011. All rights reserved.
Data Coding
• When we want to code our data (character) using bits, then the
basic formula is that we can use r bits to code 2r
characters. For
example, if we r =1, then two characters can be coded. If these
two characters are A and B then A can be coded as 0 and B
can be coded as 1 and vice versa.
• Now if we have to code the data string, ABBBBBBAAAACDEFGGGGH,
then the corresponding code would be-
• 000001001001001001001000000000000010011100101110110110110111
• This coding scheme has fixed length code because every
character is being coded using the same number of bits.
Although this technique of coding is simple but coding the data
can be made more efficient by using a variable length code.
• To do variable length encoding, we build a Huffman tree first.
First arrange all the characters in a priority queue in which the
character with highest frequency of occurrence has the lowest
weight and thus the highest priority. Then create a Huffman tree
Cod
e
Characte
r
00 A
01 B
10 C
11 D
Code Character
000 A
001 B
010 C
011 D
100 E
101 F
110 G
111 H
© Oxford University Press 2011. All rights reserved.
Data Coding contd.
• In the Huffman tree, grey nodes (internal nodes)
contain the cumulative weights of its child nodes.
Every left branch is coded with ‘0’ and every right
branch is coded with a ‘1’. So characters A, E, R,
W, X Y and Z are coded as shown in Table
E R
Z
A
X W
1
1
1
11
1
0
0
0
0
0
0
Y
Characters with their codes
Character Code
A 00
E 01
R 11
W 1010
X 1000
Y 1001
Z 1011
Thus, we see that frequent characters have a shorted code and infrequent
characters have a longer code.

More Related Content

What's hot

Data Structure and Algorithms AVL Trees
Data Structure and Algorithms AVL TreesData Structure and Algorithms AVL Trees
Data Structure and Algorithms AVL TreesManishPrajapati78
 
Search tree,Tree and binary tree and heap tree
Search tree,Tree  and binary tree and heap treeSearch tree,Tree  and binary tree and heap tree
Search tree,Tree and binary tree and heap treezia eagle
 
Data structure - Graph
Data structure - GraphData structure - Graph
Data structure - GraphMadhu Bala
 
Binary search tree operations
Binary search tree operationsBinary search tree operations
Binary search tree operationsKamran Zafar
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search TreeAbhishek L.R
 
Quick sort data structures
Quick sort data structuresQuick sort data structures
Quick sort data structureschauhankapil
 
Doubly Linked List
Doubly Linked ListDoubly Linked List
Doubly Linked ListNinad Mankar
 
Tree in data structure
Tree in data structureTree in data structure
Tree in data structureghhgj jhgh
 
THREADED BINARY TREE AND BINARY SEARCH TREE
THREADED BINARY TREE AND BINARY SEARCH TREETHREADED BINARY TREE AND BINARY SEARCH TREE
THREADED BINARY TREE AND BINARY SEARCH TREESiddhi Shrivas
 
Doubly linked list
Doubly linked listDoubly linked list
Doubly linked listFahd Allebdi
 
BINARY TREE REPRESENTATION.ppt
BINARY TREE REPRESENTATION.pptBINARY TREE REPRESENTATION.ppt
BINARY TREE REPRESENTATION.pptSeethaDinesh
 

What's hot (20)

Data Structure and Algorithms AVL Trees
Data Structure and Algorithms AVL TreesData Structure and Algorithms AVL Trees
Data Structure and Algorithms AVL Trees
 
Search tree,Tree and binary tree and heap tree
Search tree,Tree  and binary tree and heap treeSearch tree,Tree  and binary tree and heap tree
Search tree,Tree and binary tree and heap tree
 
Data structure - Graph
Data structure - GraphData structure - Graph
Data structure - Graph
 
Binary search tree operations
Binary search tree operationsBinary search tree operations
Binary search tree operations
 
B and B+ tree
B and B+ treeB and B+ tree
B and B+ tree
 
Tree Traversal
Tree TraversalTree Traversal
Tree Traversal
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
 
Quick sort data structures
Quick sort data structuresQuick sort data structures
Quick sort data structures
 
Linked list
Linked listLinked list
Linked list
 
Doubly Linked List
Doubly Linked ListDoubly Linked List
Doubly Linked List
 
Tree in data structure
Tree in data structureTree in data structure
Tree in data structure
 
THREADED BINARY TREE AND BINARY SEARCH TREE
THREADED BINARY TREE AND BINARY SEARCH TREETHREADED BINARY TREE AND BINARY SEARCH TREE
THREADED BINARY TREE AND BINARY SEARCH TREE
 
Tree and Binary Search tree
Tree and Binary Search treeTree and Binary Search tree
Tree and Binary Search tree
 
Doubly linked list
Doubly linked listDoubly linked list
Doubly linked list
 
Bfs and Dfs
Bfs and DfsBfs and Dfs
Bfs and Dfs
 
DFS and BFS
DFS and BFSDFS and BFS
DFS and BFS
 
Balanced Tree (AVL Tree & Red-Black Tree)
Balanced Tree (AVL Tree & Red-Black Tree)Balanced Tree (AVL Tree & Red-Black Tree)
Balanced Tree (AVL Tree & Red-Black Tree)
 
Tree traversal techniques
Tree traversal  techniquesTree traversal  techniques
Tree traversal techniques
 
AVL Tree
AVL TreeAVL Tree
AVL Tree
 
BINARY TREE REPRESENTATION.ppt
BINARY TREE REPRESENTATION.pptBINARY TREE REPRESENTATION.ppt
BINARY TREE REPRESENTATION.ppt
 

Similar to 358 33 powerpoint-slides_10-trees_chapter-10

Similar to 358 33 powerpoint-slides_10-trees_chapter-10 (20)

Lecture 5 tree.pptx
Lecture 5 tree.pptxLecture 5 tree.pptx
Lecture 5 tree.pptx
 
Module - 5_Trees.pdf
Module - 5_Trees.pdfModule - 5_Trees.pdf
Module - 5_Trees.pdf
 
Tree.pptx
Tree.pptxTree.pptx
Tree.pptx
 
Introduction to tree ds
Introduction to tree dsIntroduction to tree ds
Introduction to tree ds
 
Tree
TreeTree
Tree
 
Unit 5 Tree.pptx
Unit 5 Tree.pptxUnit 5 Tree.pptx
Unit 5 Tree.pptx
 
Lecture 21_Trees - I.pptx
Lecture 21_Trees - I.pptxLecture 21_Trees - I.pptx
Lecture 21_Trees - I.pptx
 
7 chapter4 trees_binary
7 chapter4 trees_binary7 chapter4 trees_binary
7 chapter4 trees_binary
 
Binary tree
Binary treeBinary tree
Binary tree
 
data_structures_and_applications_-_module-4.ppt
data_structures_and_applications_-_module-4.pptdata_structures_and_applications_-_module-4.ppt
data_structures_and_applications_-_module-4.ppt
 
Data Structures 4
Data Structures 4Data Structures 4
Data Structures 4
 
Tree chapter
Tree chapterTree chapter
Tree chapter
 
NON-LINEAR DATA STRUCTURE-TREES.pptx
NON-LINEAR DATA STRUCTURE-TREES.pptxNON-LINEAR DATA STRUCTURE-TREES.pptx
NON-LINEAR DATA STRUCTURE-TREES.pptx
 
Lecture 8 data structures and algorithms
Lecture 8 data structures and algorithmsLecture 8 data structures and algorithms
Lecture 8 data structures and algorithms
 
Unit 6 tree
Unit   6 treeUnit   6 tree
Unit 6 tree
 
Data structure using c module 2
Data structure using c module 2Data structure using c module 2
Data structure using c module 2
 
Data structures 3
Data structures 3Data structures 3
Data structures 3
 
Dsc++ unit 3 notes
Dsc++ unit 3 notesDsc++ unit 3 notes
Dsc++ unit 3 notes
 
Final tree.ppt tells about tree presentation
Final tree.ppt tells about tree presentationFinal tree.ppt tells about tree presentation
Final tree.ppt tells about tree presentation
 
Unit 3,4.docx
Unit 3,4.docxUnit 3,4.docx
Unit 3,4.docx
 

More from sumitbardhan

358 33 powerpoint-slides_15-hashing-collision_chapter-15
358 33 powerpoint-slides_15-hashing-collision_chapter-15358 33 powerpoint-slides_15-hashing-collision_chapter-15
358 33 powerpoint-slides_15-hashing-collision_chapter-15sumitbardhan
 
358 33 powerpoint-slides_14-sorting_chapter-14
358 33 powerpoint-slides_14-sorting_chapter-14358 33 powerpoint-slides_14-sorting_chapter-14
358 33 powerpoint-slides_14-sorting_chapter-14sumitbardhan
 
358 33 powerpoint-slides_12-heaps_chapter-12
358 33 powerpoint-slides_12-heaps_chapter-12358 33 powerpoint-slides_12-heaps_chapter-12
358 33 powerpoint-slides_12-heaps_chapter-12sumitbardhan
 
358 33 powerpoint-slides_7-structures_chapter-7
358 33 powerpoint-slides_7-structures_chapter-7358 33 powerpoint-slides_7-structures_chapter-7
358 33 powerpoint-slides_7-structures_chapter-7sumitbardhan
 
358 33 powerpoint-slides_6-strings_chapter-6
358 33 powerpoint-slides_6-strings_chapter-6358 33 powerpoint-slides_6-strings_chapter-6
358 33 powerpoint-slides_6-strings_chapter-6sumitbardhan
 
358 33 powerpoint-slides_5-arrays_chapter-5
358 33 powerpoint-slides_5-arrays_chapter-5358 33 powerpoint-slides_5-arrays_chapter-5
358 33 powerpoint-slides_5-arrays_chapter-5sumitbardhan
 
358 33 powerpoint-slides_4-introduction-data-structures_chapter-4
358 33 powerpoint-slides_4-introduction-data-structures_chapter-4358 33 powerpoint-slides_4-introduction-data-structures_chapter-4
358 33 powerpoint-slides_4-introduction-data-structures_chapter-4sumitbardhan
 
358 33 powerpoint-slides_3-pointers_chapter-3
358 33 powerpoint-slides_3-pointers_chapter-3358 33 powerpoint-slides_3-pointers_chapter-3
358 33 powerpoint-slides_3-pointers_chapter-3sumitbardhan
 
358 33 powerpoint-slides_2-functions_chapter-2
358 33 powerpoint-slides_2-functions_chapter-2358 33 powerpoint-slides_2-functions_chapter-2
358 33 powerpoint-slides_2-functions_chapter-2sumitbardhan
 
358 33 powerpoint-slides_1-introduction-c_chapter-1
358 33 powerpoint-slides_1-introduction-c_chapter-1358 33 powerpoint-slides_1-introduction-c_chapter-1
358 33 powerpoint-slides_1-introduction-c_chapter-1sumitbardhan
 
358 33 powerpoint-slides_16-files-their-organization_chapter-16
358 33 powerpoint-slides_16-files-their-organization_chapter-16358 33 powerpoint-slides_16-files-their-organization_chapter-16
358 33 powerpoint-slides_16-files-their-organization_chapter-16sumitbardhan
 
Algorithm analysis
Algorithm analysisAlgorithm analysis
Algorithm analysissumitbardhan
 

More from sumitbardhan (12)

358 33 powerpoint-slides_15-hashing-collision_chapter-15
358 33 powerpoint-slides_15-hashing-collision_chapter-15358 33 powerpoint-slides_15-hashing-collision_chapter-15
358 33 powerpoint-slides_15-hashing-collision_chapter-15
 
358 33 powerpoint-slides_14-sorting_chapter-14
358 33 powerpoint-slides_14-sorting_chapter-14358 33 powerpoint-slides_14-sorting_chapter-14
358 33 powerpoint-slides_14-sorting_chapter-14
 
358 33 powerpoint-slides_12-heaps_chapter-12
358 33 powerpoint-slides_12-heaps_chapter-12358 33 powerpoint-slides_12-heaps_chapter-12
358 33 powerpoint-slides_12-heaps_chapter-12
 
358 33 powerpoint-slides_7-structures_chapter-7
358 33 powerpoint-slides_7-structures_chapter-7358 33 powerpoint-slides_7-structures_chapter-7
358 33 powerpoint-slides_7-structures_chapter-7
 
358 33 powerpoint-slides_6-strings_chapter-6
358 33 powerpoint-slides_6-strings_chapter-6358 33 powerpoint-slides_6-strings_chapter-6
358 33 powerpoint-slides_6-strings_chapter-6
 
358 33 powerpoint-slides_5-arrays_chapter-5
358 33 powerpoint-slides_5-arrays_chapter-5358 33 powerpoint-slides_5-arrays_chapter-5
358 33 powerpoint-slides_5-arrays_chapter-5
 
358 33 powerpoint-slides_4-introduction-data-structures_chapter-4
358 33 powerpoint-slides_4-introduction-data-structures_chapter-4358 33 powerpoint-slides_4-introduction-data-structures_chapter-4
358 33 powerpoint-slides_4-introduction-data-structures_chapter-4
 
358 33 powerpoint-slides_3-pointers_chapter-3
358 33 powerpoint-slides_3-pointers_chapter-3358 33 powerpoint-slides_3-pointers_chapter-3
358 33 powerpoint-slides_3-pointers_chapter-3
 
358 33 powerpoint-slides_2-functions_chapter-2
358 33 powerpoint-slides_2-functions_chapter-2358 33 powerpoint-slides_2-functions_chapter-2
358 33 powerpoint-slides_2-functions_chapter-2
 
358 33 powerpoint-slides_1-introduction-c_chapter-1
358 33 powerpoint-slides_1-introduction-c_chapter-1358 33 powerpoint-slides_1-introduction-c_chapter-1
358 33 powerpoint-slides_1-introduction-c_chapter-1
 
358 33 powerpoint-slides_16-files-their-organization_chapter-16
358 33 powerpoint-slides_16-files-their-organization_chapter-16358 33 powerpoint-slides_16-files-their-organization_chapter-16
358 33 powerpoint-slides_16-files-their-organization_chapter-16
 
Algorithm analysis
Algorithm analysisAlgorithm analysis
Algorithm analysis
 

Recently uploaded

Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxAmanpreet Kaur
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxJisc
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxcallscotland1987
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdfVishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdfssuserdda66b
 

Recently uploaded (20)

Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptx
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdfVishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
 

358 33 powerpoint-slides_10-trees_chapter-10

  • 1. © Oxford University Press 2011. All rights reserved. Data Structures Using CData Structures Using C Reema TharejaReema Thareja, Assistant Professor, Institute of Information Technology and Management, New Delhi
  • 2. © Oxford University Press 2011. All rights reserved. CHAPTER 10 TREES
  • 3. © Oxford University Press 2011. All rights reserved. BINARY TREES • A binary tree is a data structure which is defined as a collection of elements called nodes. Every node contains a "left" pointer, a "right" pointer, and a data element. Every binary tree has a root element pointed by a "root" pointer. The root element is the topmost node in the tree. If root = NULL, then it means the tree is empty. • If the root node R is not NULL, then the two trees T1 and T2 are called the left and right subtrees of R. if T1 is non-empty, then T1 is said to be the left successor of R. likewise, if T2 is non-empty then, it is called the right successor of R. 8 1 32 4 5 6 7 1 2 1 0 1 1 ROOT NODE T2T1 9 In a binary tree every node has 0, 1 or at the most 2 successors. A node that has no successors or 0 successors is called the leaf node or the terminal node.
  • 4. © Oxford University Press 2011. All rights reserved. KEY TERMS • Sibling: If N is any node in T that has left successor S1 and right successor S2, then N is called the parent of S1 and S2. Correspondingly, S1 and S2 are called the left child and the right child of N. Also, S1 and S2 are said to be siblings. Every node other than the root node has a parent. In other words, all nodes that are at the same level and share the same parent are called siblings (brothers). Level number: Every node in the binary tree is assigned a level number. The root node is defined to be at level 0. The left and right child of the root node has a level number 1. Similarly, every node is at one level higher than its parents. So all child nodes are defined to have level number as parent’s level number + 1. • Degree: Degree of a node is equal to the number of children that a node has. The degree of a leaf node is zero. In-degree of a node is the number of edges arriving at that node. The root node is the only node that has an in-degree equal to zero. Similarly, Out-degree of a node is the number of edges leaving that node. Leaf node: A leaf node has no children.
  • 5. © Oxford University Press 2011. All rights reserved. KEY TERMS contd. Similar binary trees: Given two binary trees T and T’ are said to be similar if both of these trees have the same structure. A CB D E F HG I J TREE T’ TREE T” Copies of binary trees: Two binary trees T and T’ are said to be copies if they have similar structure and same contents at the corresponding nodes. A CB D E A CB D E TREE T’ TREE T”
  • 6. © Oxford University Press 2011. All rights reserved. KEY TERMS contd. • Directed edge: Line drawn from a node N to any of its successor is called a directed edge. A binary tree of n nodes have exactly n – 1 edges (because, every node except the root node is connected to its parent via an edge). • Path: A sequence of consecutive edges is called a path. • Depth: The depth of a node N is given as the length of the path from the root R to the node N. The depth of the root node is zero. The height/depth of a tree is defined as the length of the path from the root node to the deepest node in the tree. A tree with only a root node has a height of zero. A binary tree of height h, has at least h nodes and at most 2h – 1 nodes. This is because every level will have at least one node and can have at most 2 nodes. So, if every level has two nodes then a tree with height h will have at the most 2h – 1 nodes as at level 0, there is only one element called the root. The height of a binary tree with n nodes is at least n and at most log2(n+1) • Ancestor and descendant nodes: Ancestors of a node are all the nodes along the path from the root to that node. Similarly, descendants of a node are all the nodes along the path from that node to the leaf node. • Binary trees are commonly used to implement binary search trees, expression trees, tournament trees and binary heaps.
  • 7. © Oxford University Press 2011. All rights reserved. Complete Binary Trees • A complete binary tree is a binary tree which satisfies two properties. First, in a complete binary tree every level, except possibly the last, is completely filled. Second, all nodes appear as far left as possible • In a complete binary tree Tn, there are exactly n nodes and level r of T can have at most 2r nodes. • The formula to find the parent, left child and right child can be given as- if K is a parent node, then its left child can be calculated as 2 * K and its right child can be calculated as 2 * K + 1. For example, the children of node 4 are 8 (2*4) and 9 (2* 4 + 1). Similarly, the parent of the node K can be calculated as | K/2 |. Given the node 4, its parent can be calculated as | 4/2 | = 2. The height of a tree Tn having exactly n nodes is given as, • Hn = | log2 n + 1 | • This means, if a tree T has 10,00,000 nodes then its height is 21. 1 32 4 8 5 6 7 1 3 1 0 1 1 9 1 2
  • 8. © Oxford University Press 2011. All rights reserved. Extended Binary Trees • A binary tree T is said to be an extended binary tree (or a 2-tree) if each node in the tree has either no child or exactly two children. Figure shows how an ordinary binary tree is converted into an extended binary tree. • In an extended binary tree nodes that have two children are called internal nodes and nodes that have no child or zero children are called internal nodes. In the figure internal nodes are represented using a circle and external nodes are represented using squares. • To convert a binary tree into an extended tree, every empty sub-tree is replaced by a new node. The original nodes in the tree are the internal nodes and the new nodes added are called the external nodes. Binary tree Extended binary tree
  • 9. © Oxford University Press 2011. All rights reserved. Representation of Binary Trees in Memory • In computer’s memory, a binary tree can be maintained either using a linked representation (as in case of a linked list) or using sequential representation (as in case of single arrays). Linked Representation of Binary TreesLinked Representation of Binary Trees • In linked representation of binary tree, every node will have three parts, the data element, a pointer to the left node and a pointer to the right node. So in C, the binary tree is built with a node type given as below. struct node { struct node* left; int data; struct node* right; }; 1 2 3 4 5 6 7 X 8 X X 9 X X 10 X X 11 X X 12 X
  • 10. © Oxford University Press 2011. All rights reserved. Sequential Representation of Binary Trees • Sequential representation of trees is done using single or one dimensional array. Though, it is the simplest technique for memory representation but it is very inefficient as it requires a lot of memory space. A sequential binary tree follows the rules given below: • One dimensional array called TREE, will be used. • The root of the tree will be stored in the first location. That is, TREE[0] will store the data of the root element. • The children of a node K, will be stored in location (2*K) and (2*K+1). • The maximum size of the array TREE is given as (2d+1 -1), where d is the depth of the tree. • An empty tree or sub-tree is specified using NULL. If TREE[0] = NULL, then the tree is empty. 3515 12 17 2 1 3 9 4 51 6 1 8 3 6 20 0 20 1 2 15 3 35 4 12 5 17 6 21 7 39 8 9 10 16 11 18 12 13 14 36 15 45 16 17 18
  • 11. © Oxford University Press 2011. All rights reserved. EXPRESSION TREES • Binary trees are widely used to store algebraic expressions. For example, consider the algebraic expression Exp given as, • Exp = (a – b ) + ( c * d) • This expression can be represented using a binary tree as shown in figure + *- a b c d
  • 12. © Oxford University Press 2011. All rights reserved. TOURNAMENT TREES • In a tournament tree (also called a selection tree), each external node represents a player and each internal node represents the winner of the match played between the players represented by its children nodes. These tournament trees are also called winner trees because they are being used to record the winner at each level. We can also have a loser tree that records the loser at each level. a ea a a d e g fc db e hg
  • 13. © Oxford University Press 2011. All rights reserved. TRAVERSING OF A BINARY TREE • Traversing a binary tree is the process of visiting each node in the tree exactly once, in a systematic way. Unlike linear data structures in which the elements are traversed sequentially, tree is a non-linear data structure in which the elements can be traversed in many different ways. There are different algorithms for tree traversals. These algorithms differ in the order in which the nodes are visited. In this section, we will read about these algorithms. • Pre-order algorithm To traverse a non-empty binary tree in preorder, the following operations are performed recursively at each node. The algorithm starts with the root node of the tree and continues by, • Visiting the root node. • Traversing the left subtree. • Traversing the right subtree. A CB D E F IH GA, B, D, C, E, F, G, H and I
  • 14. © Oxford University Press 2011. All rights reserved. In-order algorithm To traverse a non-empty binary tree in in-order, the following operations are performed recursively at each node. The algorithm starts with the root node of the tree and continues by, • Traversing the left subtree. • Visiting the root node. • Traversing the right subtree. Post-order algorithm To traverse a non-empty binary tree in post-order, the following operations are performed recursively at each node. The algorithm starts with the root node of the tree and continues by, • Traversing the left subtree. • Traversing the right subtree. • Visiting the root node. A CB D E F IH G B, D, A, E, H, G, I, F AND C. D, B, H, I, G, F, E, C and A.
  • 15. © Oxford University Press 2011. All rights reserved. HUFFMAN’S TREE • Huffman coding is an entropy encoding algorithm developed by David A. Huffman that is widely used as a lossless data compression technique. The Huffman coding algorithm uses a variable-length code table to encode a source character where the variable-length code table is derived in a particular way based on the estimated probability of occurrence for each possible value of the source character. • The key idea behind the Huffman algorithm is that it encodes the most common characters using shorter strings of bits than are used for less common source characters. • The algorithm works by creating a binary tree of nodes that are stored in a regular array. The size of this array depends on the number of number of nodes in the tree. • The external path length of a binary tree is defined as the sum of all path lengths summed over each path from the root to the external node. The internal path length is also defined in the same manner. The internal path length of a binary tree is defined as the sum of all path lengths summed over each path from the root to the internal node.
  • 16. © Oxford University Press 2011. All rights reserved. • The internal path length, LI = 0 + 1 + 2 + 1 + 2 + 3 + 3 = 12 • The external path length, LE = 2 + 3 + 3 + 2 + 4 + 4 + 4 + 4 = 26 • Note that, LI + 2 * n = 12 + 2 * 7 = 12 + 14 = 26 = LE • Hence, the formula is LI + 2n = LE, where n is the number of internal nodes. • Now if the tree with n external nodes is assigned a weight, then the weighted path length, P is defined as the sum of the weighted path lengths. • Therefore, P = W1L1 + W2L2 + …. + WnLn, • where, Wi and Li are the weight and path length of the external node Ni. The Huffman Algorithm Step 1: Create a leaf node for each character. Add the character and its weight or frequency of occurrence to the priority queue. Step 2: Repeat Steps 3 to 5 while the total number of nodes in the queue is greater than 1 Step 3: Remove two nodes that have the lowest weight (or highest priority) Step 4: Create a new internal node by merging these two nodes as children and with weight equal to the sum of the two nodes' weights. Step 5: Add the newly created node to the queue.
  • 17. © Oxford University Press 2011. All rights reserved. Data Coding • When we want to code our data (character) using bits, then the basic formula is that we can use r bits to code 2r characters. For example, if we r =1, then two characters can be coded. If these two characters are A and B then A can be coded as 0 and B can be coded as 1 and vice versa. • Now if we have to code the data string, ABBBBBBAAAACDEFGGGGH, then the corresponding code would be- • 000001001001001001001000000000000010011100101110110110110111 • This coding scheme has fixed length code because every character is being coded using the same number of bits. Although this technique of coding is simple but coding the data can be made more efficient by using a variable length code. • To do variable length encoding, we build a Huffman tree first. First arrange all the characters in a priority queue in which the character with highest frequency of occurrence has the lowest weight and thus the highest priority. Then create a Huffman tree Cod e Characte r 00 A 01 B 10 C 11 D Code Character 000 A 001 B 010 C 011 D 100 E 101 F 110 G 111 H
  • 18. © Oxford University Press 2011. All rights reserved. Data Coding contd. • In the Huffman tree, grey nodes (internal nodes) contain the cumulative weights of its child nodes. Every left branch is coded with ‘0’ and every right branch is coded with a ‘1’. So characters A, E, R, W, X Y and Z are coded as shown in Table E R Z A X W 1 1 1 11 1 0 0 0 0 0 0 Y Characters with their codes Character Code A 00 E 01 R 11 W 1010 X 1000 Y 1001 Z 1011 Thus, we see that frequent characters have a shorted code and infrequent characters have a longer code.