SlideShare une entreprise Scribd logo
1  sur  64
Unit – VI Tree
Prepared By:
Dabbal Singh Mahara
1
a. Concept and definition
b. Binary tree
c. Introduction and application
d. Operations
e. Types of binary tree
 Complete binary tree
 Strictly binary tree
 Almost complete binary tree
f. Tree traversal
 Pre-order traversal
 In-order traversal
 Post-order traversal
g. Binary search tree
 searching
 insertion
 deletion
h. Expression Tree
i. Huffman algorithm
j. AVL Trees
Tree data structure
2By Dabal Mahara
Introduction
• A tree is an abstract model of a hierarchical structure that consists of
nodes with a parent-child relationship. A tree is a finite set of data
items or nodes such that:
 There is a special data-item called the root of the tree
 Its remaining data items are partitioned into mutually exclusive sub-
sets, each of which itself is a tree, called sub-trees.
Characteristics of trees:
 Non-linear data structure
 Combines advantages of an ordered array
 Searching as fast as in ordered array
 Insertion and deletion as fast as in linked list
Application:
 Directory structure of a file store
 Structure of arithmetic expressions
 Hierarchy of an organization
Some key terms
 Degree of a node:
The degree of a node is the number of children of that node. In above tree ,
degree(A) = 2.
 Degree of a Tree:
The degree of a tree is the maximum degree of nodes in a given tree. In the
above tree, maximum degree of nodes is 2, thus the degree of the tree is 2.
 Path:
It is the sequence of consecutive edges from source node to destination node.
There is a single unique path from the root to any node.
4By Dabal Mahara
Height of a node:
The height of a node is the maximum path length from that node to
a leaf node. A leaf node has a height of 0.
 Height of a tree:
The height of a tree is the height of the root.
 Depth of a node:
Depth of a node is the path length from the root to that node. The
root node has a depth of 0.
 Depth of a tree:
Depth of a tree is the maximum level of any leaf in the tree. This is
equal to the longest path from the root to any leaf.
Level of a node:
The level of a node is 0, if it is root; otherwise it is one more then its
parent.
5By Dabal Mahara
• A is the root node
• B is the parent of E and F
• D is the sibling of B and C
• E and F are children of B
• E, F, G, D are external nodes or leaves
• A, B, C are internal nodes
• Depth of F is 2
• the height of tree is 2
• the degree of node A is 3
• The degree of tree is 3
Illustration:
6By Dabal Mahara
Binary Trees
 A binary tree is a finite set of elements that are either empty or is
partitioned into three disjoint subsets.
 The first subset contains a single element called the root of the tree.
 The other two subsets are themselves binary trees called the left
and right sub-trees of the original tree. A left or right sub tree can be
empty.
 Each element of a binary tree is called a node of the tree. The
following figure shows a binary tree with 9 nodes where A is the
root.
7By Dabal Mahara
Binary tree properties:
 If a binary tree contains m nodes at level l , it contains at
most 2m nodes at level l + 1.
 Since a binary tree can contain at most 1 node at level 0 (the
root), it contains at most 2l nodes at level l.
Types of binary tree
 Strictly binary tree
 Almost complete binary tree
 Complete binary tree
8By Dabal Mahara
 If every non-leaf node in a binary tree has non-empty left and right
sub-trees, then such a tree is called a strictly binary tree.
Strictly binary tree
 The following tree is not strictly binary tree, Since node E has a left son
but not a right son.
9By Dabal Mahara
 A strictly binary tree of depth d is called complete binary
tree if all of whose leaves are at level d.
 A complete binary tree with depth d has 2d leaves and 2d -1
non-leaf nodes (internal).
Complete binary tree:
Example: In this tree d = 3,
therefore, leaves = 23 = 8 Internal nodes = 23 -1 = 7
10By Dabal Mahara
A binary tree of depth d is an almost complete binary tree if:
i. Any node at level less than d-1 has two sons.
ii. For any node in the tree with a right descendant at level d, the node must
have a left son and every left descendant of the node is either a leaf at level
d or has two sons.
Almost complete binary tree:
11By Dabal Mahara
B
J
G
F
C
I
ED
H
A
K
Level 0
Level 1
Level 2
Level 3
This tree is not almost complete binary tree because it does not
satisfy condition ii.
That is, node A has right descendent at level 3 ( J or K), but it has left
descendent leaf node at level 2 (node E).
12By Dabal Mahara
Operations on Binary tree:
 father(n,T): Return the parent node of the node n in tree T. If n is the
root, NULL is returned.
 LeftChild(n,T): Return the left child of node n in tree T. Return NULL if n
does not have a left child.
 RightChild(n,T): Return the right child of node n in tree T. Return NULL if n
does not have a right child.
 Info(n,T): Return information stored in node n of tree T (ie. Content of
a node).
 Sibling(n,T): return the sibling node of node n in tree T. Return NULL if n
has no sibling.
 Root(T): Return root node of a tree if and only if the tree is
nonempty.
 Size(T): Return the number of nodes in tree T
 MakeEmpty(T): Create an empty tree T
 SetLeft(S,T): Attach the tree S as the left sub-tree of tree T
 SetRight(S,T): Attach the tree S as the right sub-tree of tree T.
 Preorder(T): Traverses all the nodes of tree T in preorder.
 postorder(T): Traverses all the nodes of tree T in postorder
 Inorder(T): Traverses all the nodes of tree T in inorder.
13By Dabal Mahara
• Array representation
• Linked Representation
Binary Tree Representation
Array Representation
An array is used to store the nodes of the binary tree. Nodes stored in the
array are accessed sequentially, root is at index 0 and then left child and
right child are stored. To store the elements of the binary tree of depth d,
declare the array of size 2d+1 -1, i.e. the total number of nodes of complete
binary tree and store the elements level wise. If root is at I then left child is t
2i+1 and right child is at 2i+2.
B
J
G
F
C
I
ED
H
A0
1 2
4
7
5
14
6
3
10
Declare array of size 2 3+1 -1 = 15
Char a[15]
A B C D E F G H I J
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 14By Dabal Mahara
Linked Representation of Binary Tree
• It is the most popular way to present a binary tree. Each element is
represented by a node that has two link fields (leftChild and rightChild)
plus an element field. Each binary tree node is represented as an object
whose data type is binaryTreeNode .
• The space required by an n node binary tree is: n * sizeof(binaryTreeNode)
C representation for Binary tree
struct binaryTreeNode
{
int info;
struct binaryTreenode *left;
struct binaryTreenode *right;
};
struct binaryTreenode *root=NULL;
15By Dabal Mahara
The given tree can be represented in linked list as
given below.
16By Dabal Mahara
 The tree traversal is a way in which each node in the
tree is visited exactly once in a symmetric manner.
 There are three popular methods of traversal
i. Pre-order traversal
ii. In-order traversal
iii. Post-order traversal
Tree traversal
17By Dabal Mahara
1. Pre-order traversal:
The preorder traversal of a nonempty binary tree is defined as
follows:
i. Visit the root node
ii. Traverse the left sub-tree in preorder
iii. Traverse the right sub-tree in preorder
The preorder traversal output of the given tree
is: A B D H I E C F G
The preorder is also known as depth first order.
C function for preorder traversing:
void preorder(struct bnode *root)
{
if(root!=NULL)
{
printf(“%c”, root->info);
preorder(root->left);
preorder(root->right);
}
}
18By Dabal Mahara
The inorder traversal of a nonempty binary tree is defined as follows:
i. Traverse the left sub-tree in inorder
ii. Visit the root node
iii. Traverse the right sub-tree in inorder
The inorder traversal output of the given tree
is: H D I B E A F C G
C function for inorder traversing:
void inorder(struct binaryTreenode *root)
{
if(root!=NULL)
{
inorder(root->left);
printf(“%c”, root->info);
inorder(root->right);
}
}
2. In-order traversal:
19By Dabal Mahara
3. Post-order traversal:
The post-order traversal of a nonempty binary tree is defined as follows:
i. Traverse the left sub-tree in post-order
ii. Traverse the right sub-tree in post-order
iii. Visit the root node
C function for post-order traversing:
void post-order(struct bnode *root)
{
if(root!=NULL)
{
post-order(root->left);
post-order(root->right);
printf(“%c”, root->info);
}
}
The post-order traversal output of the given tree
is: H I D E B F G C A
20By Dabal Mahara
Q. Design a binary tree whose traversal sequences are
given below:
Pre-order: CPRBLOEMATIK
In-Order: BRLPEOMCTAIK
Solution:
Since preorder traverses from root of the tree, C is root of the tree.
The { B, R, L, P, E, O, M} and {T, I, A, K } are respectively left and right sub
tree . (from inorder sequence)
C
T, A,
I, K
B, R, L,
P, E, O,
M
21By Dabal Mahara
C
I, KB, R, L,
P
E, O, M
A
T
Similarly, for left sub tree { B, R, L, P, E, O, M}, root is P ( from preorder sequence)
and {B, R, L} is left sub-tree and {E, O, M} is right sub-tree. ( From inorder sequence)
For right sub-tree {T, A, I, K}, A is the root. ( from preorder sequence)
T is left sub-tree and {I, K } is right sub-tree.
22By Dabal Mahara
Similarly, R is root for sub-tree {B, R, L} ( from preorder sequence)
B is left child and L right child of R ( from inorder sequence)
O is root for sub-tree {E, O, M} (from preorder sequence)
E is left child and M is right child of O (from inorder sequence)
In the same way, I is root and K is right child for sub-tree { I, K }
C
P A
TO I
KL M
R
EB
23By Dabal Mahara
Q. A binary tree T has 12 nodes. The in-order and post-order traversals of T
yield the following sequence of nodes:
In-order : VPNAQRSOKBTM
Post-order : VANRQPBKOMTS
Construct the Binary tree T showing each step. Explain how you can arrive
at solution in brief.
Solution:
Since post-order traversal visits all nodes in left sub-tree , right sub-tree
and root recursively, the last node in the sequence is root of the tree. That
is, S is the root.
In-order traversal visits the nodes in Left child, root and right child in
recursive way, { V,P, N,A, Q, R} is left sub-tree and {O, K, B, T, M} is the right
sub tree.
S
O, K,
B, T,
M
V, P, N,
A, Q, R
Step -1:
24By Dabal Mahara
S
O, K,
B
P T
MV
N, A, Q, R
O
S
K, B
P
N, A
T
MV Q
R
Step -2: The root of { V, P, N, A, Q, R} is P obtained from postorder sequence. Left subtree and right
sub trees are {v} and {N, A, Q, R} obtained from inorder sequence.
Similarly, for { O, K, T, B, M} , root is T and left sub tree {O, K, B} and right sub tree is {M}.
Step -3: In the same way, root and sub trees are obtained.
25By Dabal Mahara
S
P T
MV Q
R
Step -4: The final tree is given below.
O
K
B
A
N
Thus, root of the tree is obtained from post-order sequence scanning
from right to left and left and right sub-trees of corresponding root are
obtained from inorder sequence.
26By Dabal Mahara
An important application of binary trees is their use in searching.
A binary search tree (BST) is a binary tree that is either empty or in
which every node contains a key (value) and satisfies the following
conditions:
i. All keys in the left sub-tree of the root are smaller than the
key in the root node.
ii. All keys in the right sub-tree of the root are greater than the
key in the root node.
iii. The left and right sub-trees of the root are again binary search
trees .
Binary search tree(BST)
27By Dabal Mahara
Binary Search Trees
1 4
2
3
8
6
1 4
2
3
8
6
7
• The tree on the left is a binary search tree, but the tree on
the right is not.
28By Dabal Mahara
Given the following sequence of numbers, 14, 15, 4, 9, 7, 18, 3, 5, 16, 20, 17, 5
The following binary search tree can be constructed:
14
4
9
15
7
5 17
2016
3 18
The inorder traversal of BST gives the sorted sequence in ascending order.
So, inorder traversal of above BST is: 3, 4, 5, 7, 9, 14, 15, 16, 17, 18, 20.
29By Dabal Mahara
Following operations can be done in BST:
 Search(k, T): Search for key k in the tree T. If k is found in some node
of tree then return true otherwise return false.
 Insert(k, T): Insert a new node with value k in the info field in the tree
T such that the property of BST is maintained.
 Delete(k, T):Delete a node with value k in the info field from the tree T
such that the property of BST is maintained.
 FindMin(T), FindMax(T): Find minimum and maximum element from
the given nonempty BST.
Operations on Binary search tree(BST):
30By Dabal Mahara
struct bstnode
{
int info; //Declaring an info field
struct bstnode *left; // left child pointer
struct bstnode *right; // right child pointer
};
Structure of BST node
Struct bstnode *root = NULL;
31By Dabal Mahara
To find if any node of a BST contains an element equal to target:
1. Set curr to the BST’s root.
2. Repeat:
2.1. If curr is null:
2.1.1. Terminate with answer none.
2.2. Otherwise, if target is equal to curr’s element:
2.2.1. Terminate with answer curr.
2.3. Otherwise, if target is less than curr’s element:
2.3.1. Set curr to curr’s left child.
2.4. Otherwise, if target is greater than curr’s element:
2.4.1. Set curr to curr’s right child.
2. end
BST search algorithm :
32By Dabal Mahara
C function for BST searching:
void BinSearch(struct bstnode *root , int key)
{
if(root == NULL)
{
printf(“The number does not exist”);
}
else if (key == root->info)
{
printf(“The searched item is found”):
}
else if(key < root->info)
BinSearch(root->left, key);
else
BinSearch(root->right, key);
}
33By Dabal Mahara
To insert a new item in a tree, we must first verify that its key is different from
those of existing elements. To do this a search is carried out. If the search is
unsuccessful, then item is inserted.
Idea: To insert a new element into a BST, proceed as if searching for that
element. If the element is not already present, the search will lead to a null
link. Replace that null link by a link to a leaf node containing the new element.
Insertion of a node in BST:
15
9
13
12
10
18
20
22
25
Insertion of element 13
34By Dabal Mahara
To insert the element elem into a BST:
1. Set parent to null, and set curr to the BST’s root.
2. Repeat:
2.1. If curr is null:
2.1.1. Replace the null link from which curr was taken
(either the BST’s root or parent’s left child or parent’s
right child) link to a newly-created leaf node with
element elem.
2.1.2. Terminate.
2.2. Otherwise, if elem is equal to curr’s element:
2.2.1. Terminate.
2.3. Otherwise, if elem is less than curr’s element:
2.3.1. Set parent to curr, and set curr to curr’s left child.
2.4. Otherwise, if elem is greater than curr’s element:
2.4.1. Set parent to curr, and set curr to curr’s right child.
3.End
BST insertion algorithm :
35By Dabal Mahara
C function for BST insertion:
Struct bstnode * insert(struct bstnode *root, int item)
{
if(root=NULL)
{
root=(struct bstnode*)malloc (sizeof(struct bnode));
root->left=root->right=NULL;
root->info=item;
}
else if ( item == root->info)
{
printf("n Duplicate not allowed.");
return root;
}
else
{
if(item<root->info)
root->left=insert(root->left, item);
else
root->right=insert(root->right, item);
}
}
36By Dabal Mahara
While deleting a node from BST, there may be three cases:
1. The node to be deleted may be a leaf node:
In this case simply delete a node and set null pointer to its parents those
side at which this deleted node exist.
Deleting a node from the BST:
37By Dabal Mahara
2. The node to be deleted has one child:
In this case the child of the node to be deleted is appended to its parent
node.
Suppose node to be deleted is 18
Delete(18)
38By Dabal Mahara
3. The node to be deleted has two children:
In this case node to be deleted is replaced by its in-order successor node.
That is, the node to be deleted is either replaced by its right sub-trees leftmost
node or its left sub-trees rightmost node.
Suppose node to deleted is 12. Find minimum element in the right sub-tree of
the node to be removed. In current example it is 19.
Delete(12)
39By Dabal Mahara
General algorithm to delete a node from a BST:
1. start
2. if a node to be deleted is a leaf node at left side then simply delete and set null
pointer to it's parent's left pointer.
3. If a node to be deleted is a leaf node at right side then simply delete and set
null pointer to it's parent's right pointer.
4. if a node to be deleted has one child then connect it's child pointer with it's
parent pointer and delete it from the tree.
5. if a node to be deleted has two children then replace the node being deleted
either by
a. right most node of it's left sub-tree or
b. left most node of it's right sub-tree.
6. End
40By Dabal Mahara
The delnode function:
struct bstnode *delnode(struct bstnode *root, int item)
{
struct bstnode *temp;
if(root==NULL)
{
printf(“Empty tree”);
return;
}
else if(item<root->info)
root->left=delnode(root->left, item);
else if(item>root->info)
root->right=delnode(root->right, item);
else if(root->left!=NULL && root->right!=NULL) //node has two children
{
temp=findmin(root->right);
root->info=temp->info;
root->right=delnode(root->right, root->info);
}
else
{
temp=root;
if(root->left==NULL)
root=root->right;
else if(root->right==NULL)
root=root->left;
free(temp);
}
return(root);
} 41By Dabal Mahara
struct bstnode * findmin(struct bstnode * root)
{
if(root==NULL)
return NULL;
else if(root->left ==NULL)
return head;
else
return(findmin(root->left));
}
42By Dabal Mahara
Expression Tree
An expression tree is a strictly binary tree in which leaf node contains operands
and non-leaf node contain operators. Root nodes contain the operators that is
applied to the result of left and right sub trees. The operators, constants, and
variables are arranged in such a way that an inorder traversal of the tree
produces the original expression without parentheses.
Example: 1 An expression tree of an expression (a + b *c ) +((c*e +f) *g)
*a
+ *
g+
f
*
ec
c
+
b
Exercise: Construct an expression tree of an expression: (a + b ) /((c-d) *e)
43By Dabal Mahara
Expression Tree Examples
Inorder Traversal ResultExpression TreeExpression
a + 3(a+3)
3+4*5-9+63+(4*5-(9+6))
log xlog(x)
n !n!
+
3a
+
-3
*
54
+
69
log
x
!
n
44By Dabal Mahara
Constructing an Expression Tree From
Postfix Expression
Algorithm
• We read the expression one symbol at a time.
• If the symbol is an operand, we create a one-node tree and push a pointer
to it onto a stack.
• If the symbol is an operator, we pop pointers to two trees T1 and T2 from
the stack (T1 is popped first) and form a new tree whose root is the
operator and whose left and right children point to T2 and T1, respectively.
A pointer to this new tree is then pushed onto the stack.
45By Dabal Mahara
Example:
• Input: 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.
a b
 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.
a b
+
 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.
a b
+ c d e
46By Dabal Mahara
Constructing an Expression Tree
a b
+ c
• Now a ‘+’ is read, so two trees are merged.
d e
+
a b
+
c
 Continuing, a ‘*’ is read, so we pop two tree pointers and form a new
tree with a ‘*’ as root.
d e
+
*
47By Dabal Mahara
Constructing an Expression Tree
a b
+
c
 Finally, the last symbol is read, two trees are merged, and a pointer to
the final tree is left on the stack.
d e
+
*
*
Exercise: Construct an expression from postfix expression:
AB+C*DC--FG+$
48By Dabal Mahara
• Proposed by Dr. David A. Huffman at MIT in 1952
– “A Method for the Construction of Minimum Redundancy Codes”
• Huffman coding is a form of statistical coding
– more frequently used symbols have shorter code words
– Not all characters occur with the same frequency!
– Yet all characters are allocated the same amount of space
– 1 char = 1 byte, be it e or x
• Huffman coding is a technique used to compress files for transmission
• Works well for text and fax transmissions
The Huffman Coding
49By Dabal Mahara
Huffman Algorithm
1. Initially, each symbol is one node tree by itself. That is, there is forest of n nodes
each labelled with symbol and weight.
2. Repeat while n>1
i. Select the two trees T1 and T2 with minimum weights from the forest.
ii. Merge T1 and T2 to form T3 with weight sum of both trees.
iii. Insert T3 into the forest.
3. Assign 0 to each left path of tree and 1 to right path. The code for each symbol
is obtained by collecting bits on the paths from root to the leaf node labelled
with the symbol.
• Huffman codes is text compression method, which relies on the relative frequency
(i.e., the number of occurrences of a symbol) with which different symbols appear
in a text
• Uses extended binary trees
• Variable-length codes that satisfy the property, where no code is a prefix of another
• Huffman tree is a binary tree with minimum weighted external path length for a
given set of frequencies (weights).
Huffman Code
50By Dabal Mahara
Example: 1
Let us take any four characters and their frequencies as follows:
Char frequency
E 10
T 7
O 5
A 3
• Without using Huffman coding, these four characters can be represented by using
two bits as: 00 -> E, T ->01, O ->10 and A-> 11. This is fixed length coding. So, bits
required to encode all the characters in the above message will be:
( 10 +7+5+3) * 2 = 50 bits
• Huffman coding technique uses variable length code depending upon the
frequency of characters used in the text. It's coding technique is as follows:
First sort the characters by their frequency in non-decreasing order.
Char frequency
A 3
O 5
T 7
E 10
51By Dabal Mahara
1. Create a forest of one node trees for each character as:
A : 3 O : 5 T : 7 E: 10
2. Merge two minimum trees as a single tree and add it to the forest in the
order.
T1 : 8
O: 5A : 3
T : 7 E: 10
3. Repeat step 2 again.
T2 : 15
T : 7
T1 : 8
O: 5A : 3
E: 10
52By Dabal Mahara
4. Repeat the step 2 again.
T3: 25
E: 10
T2 : 15
T : 7
T1 : 8
O: 5A : 3
T3: 25
E: 10
T2 : 15
T : 7
T1 : 8
O: 5A : 3
5. Assign 0 to left path and 1 to right path in the tree.
0
0
0
1
1
1
This tree is called Huffman tree.
53By Dabal Mahara
Now the code for each characters are as obtained by collecting the bits from
root to the character node. The codes are:
Char code frequency
E 0 10
T 10 7
A 110 3
O 111 5
Therefore, total number of bits required = 10* 1 +7 *2 + 3 *3 + 5 *3 =48 bits
The space saved = (50-48)/50 *100 % = 4 %
54By Dabal Mahara
Example: 2
Let us take any four characters and their frequencies as follows:
Char frequency
a 10
e 15
i 12
s 3
t 4
Sp (space) 13
nl (new line) 1
Fixed Length Format: These 7 characters can be represented by three bits.
So, total number of bits = (10+15+12+3+4+13+1) * 3 = 174
Using Huffman Coding
First sort the characters by their frequency in non-decreasing order.
Char frequency
nl (new line) 1
s 3
t 4
a 10
i 12
Sp (space) 13
e 15
55By Dabal Mahara
1. Create a forest of one node trees for each character as:
2. Merge two minimum trees as a single tree and add it to the forest in the
order.
T1 : 4
S : 3
nl :
1
3. Repeat step 2 again.
nl :
1
s:
3
t :
4
a:
10
i:
12
sp:
13
e:
15
t :
4
a:
10
i:
12
sp:
13
e:
15
a:
10
i: 12
sp:
13
e:
15
T2 : 8
T1 : 4
S : 3
nl :
1
t :
4
56By Dabal Mahara
4. Repeat step 2 again.
i: 12 sp: 13 e: 15
T2 : 8
T1 : 4
S : 3nl : 1
t : 4
T3 : 18
a : 10
5. Repeat step 2 again.
e: 15 T4:
25
sp: 13i: 12
T2 : 8
T1 : 4
S : 3nl : 1
t : 4
T3 : 18
a : 10
57By Dabal Mahara
6. Repeat step 2 again.
sp: 13
T4:
25
i: 12 T2 : 8
T1 : 4
S : 3nl : 1
t : 4
T3 : 18
a : 10
e: 15
T5: 33
58By Dabal Mahara
sp: 13
T4:
25
i: 12 T2 : 8
T1 : 4
S : 3nl : 1
t : 4
T3 : 18
a : 10
e: 15
T5: 33
T6: 58
7. Repeat step 2 again.
59By Dabal Mahara
sp: 13
T4:
25
i: 12 T2 : 8
T1 : 4
S : 3nl : 1
t : 4
T3 : 18
a : 10
e: 15
T5: 33
T6: 58
8. Assign 0 to left path and 1 to right path in the tree.
0
1
0
0
0
0
0 1
1
1
1
1
This tree is called Huffman tree.
60By Dabal Mahara
Now the code for each characters are as obtained by collecting the bits from
root to the character node. The codes are:
Char code frequency
i 00 12
sp 01 13
e 10 15
nl 11000 1
S 11001 3
t 1101 4
a 111 10
Therefore, total number of bits required
= 12*2 +13 *2 + 15 *2 + 1 *5 +3 * 5 + 4*4 + 10 * 3
= 146 bits
The space saved = (174-146)/174 *100 %
= 16.09 %
61By Dabal Mahara
AVL (Adelson-Velskii and Landis) Trees
• An AVL Tree is a
binary search tree
such that for every
internal node v of T,
the heights of the
children of v can differ
by at most 1.
88
44
17 78
32 50
48 62
2
4
1
1
2
3
1
1
An example of an AVL tree where the
heights are shown next to the nodes:
62By Dabal Mahara
5
3 8
1 4 10
AVL Tree
5
3
1 4
Not AVL Tree
• All operations depend on the depth of the tree.
• BSTs are limited because of their bad worst-case performance O(n).
• AVL trees are height-balanced binary search trees
• An AVL tree has balance factor calculated at every node
For every node, heights of left and right subtree can differ by no
more than 1
• It allows dynamic insert and remove with O(log(N)) time
complexity.
• Balanced search trees are trees whose heights in the worst case is
O(lg n)
63By Dabal Mahara
64By Dabal Mahara

Contenu connexe

Tendances (20)

VCE Unit 03vv.pptx
VCE Unit 03vv.pptxVCE Unit 03vv.pptx
VCE Unit 03vv.pptx
 
Binary trees
Binary treesBinary trees
Binary trees
 
binary search tree
binary search treebinary search tree
binary search tree
 
VCE Unit 04vv.pptx
VCE Unit 04vv.pptxVCE Unit 04vv.pptx
VCE Unit 04vv.pptx
 
Searching Techniques and Analysis
Searching Techniques and AnalysisSearching Techniques and Analysis
Searching Techniques and Analysis
 
B and B+ tree
B and B+ treeB and B+ tree
B and B+ tree
 
VCE - UNIT-II.pptx
VCE - UNIT-II.pptxVCE - UNIT-II.pptx
VCE - UNIT-II.pptx
 
Tree and binary tree
Tree and binary treeTree and binary tree
Tree and binary tree
 
Binary tree traversal ppt
Binary tree traversal pptBinary tree traversal ppt
Binary tree traversal ppt
 
Tree Traversal
Tree TraversalTree Traversal
Tree Traversal
 
Binary tree
Binary  treeBinary  tree
Binary tree
 
AVL Tree Data Structure
AVL Tree Data StructureAVL Tree Data Structure
AVL Tree Data Structure
 
Binary trees1
Binary trees1Binary trees1
Binary trees1
 
linear search and binary search
linear search and binary searchlinear search and binary search
linear search and binary search
 
2 3 tree
2 3 tree2 3 tree
2 3 tree
 
Binary tree traversal ppt - 02.03.2020
Binary tree traversal   ppt - 02.03.2020Binary tree traversal   ppt - 02.03.2020
Binary tree traversal ppt - 02.03.2020
 
Binary tree
Binary tree Binary tree
Binary tree
 
13. Indexing MTrees - Data Structures using C++ by Varsha Patil
13. Indexing MTrees - Data Structures using C++ by Varsha Patil13. Indexing MTrees - Data Structures using C++ by Varsha Patil
13. Indexing MTrees - Data Structures using C++ by Varsha Patil
 
Trees
TreesTrees
Trees
 
Data structure - Graph
Data structure - GraphData structure - Graph
Data structure - Graph
 

En vedette

System Programming Unit III
System Programming Unit IIISystem Programming Unit III
System Programming Unit IIIManoj Patil
 
System Programing Unit 1
System Programing Unit 1System Programing Unit 1
System Programing Unit 1Manoj Patil
 
System Programming Unit II
System Programming Unit IISystem Programming Unit II
System Programming Unit IIManoj Patil
 
Binary expression tree
Binary expression treeBinary expression tree
Binary expression treeShab Bi
 

En vedette (6)

Tree
TreeTree
Tree
 
Single Pass Assembler
Single Pass AssemblerSingle Pass Assembler
Single Pass Assembler
 
System Programming Unit III
System Programming Unit IIISystem Programming Unit III
System Programming Unit III
 
System Programing Unit 1
System Programing Unit 1System Programing Unit 1
System Programing Unit 1
 
System Programming Unit II
System Programming Unit IISystem Programming Unit II
System Programming Unit II
 
Binary expression tree
Binary expression treeBinary expression tree
Binary expression tree
 

Similaire à Unit – vi tree

Similaire à Unit – vi tree (20)

Unit 6 tree
Unit   6 treeUnit   6 tree
Unit 6 tree
 
binary tree.pptx
binary tree.pptxbinary tree.pptx
binary tree.pptx
 
Lecture 8 data structures and algorithms
Lecture 8 data structures and algorithmsLecture 8 data structures and algorithms
Lecture 8 data structures and algorithms
 
Lecture-7-Binary-Trees-and-Algorithms-11052023-054009pm.pptx
Lecture-7-Binary-Trees-and-Algorithms-11052023-054009pm.pptxLecture-7-Binary-Trees-and-Algorithms-11052023-054009pm.pptx
Lecture-7-Binary-Trees-and-Algorithms-11052023-054009pm.pptx
 
Unit 3.ppt
Unit 3.pptUnit 3.ppt
Unit 3.ppt
 
07 trees
07 trees07 trees
07 trees
 
non linear data structure -introduction of tree
non linear data structure -introduction of treenon linear data structure -introduction of tree
non linear data structure -introduction of tree
 
Tree and Binary Search tree
Tree and Binary Search treeTree and Binary Search tree
Tree and Binary Search tree
 
Dsc++ unit 3 notes
Dsc++ unit 3 notesDsc++ unit 3 notes
Dsc++ unit 3 notes
 
Lecture 21_Trees - I.pptx
Lecture 21_Trees - I.pptxLecture 21_Trees - I.pptx
Lecture 21_Trees - I.pptx
 
NON-LINEAR DATA STRUCTURE-TREES.pptx
NON-LINEAR DATA STRUCTURE-TREES.pptxNON-LINEAR DATA STRUCTURE-TREES.pptx
NON-LINEAR DATA STRUCTURE-TREES.pptx
 
Tree
TreeTree
Tree
 
Chapter 8 ds
Chapter 8 dsChapter 8 ds
Chapter 8 ds
 
DSA-Unit-2.pptx
DSA-Unit-2.pptxDSA-Unit-2.pptx
DSA-Unit-2.pptx
 
Data structure using c module 2
Data structure using c module 2Data structure using c module 2
Data structure using c module 2
 
AD3251-Data Structures Design-Notes-Tree.pdf
AD3251-Data Structures  Design-Notes-Tree.pdfAD3251-Data Structures  Design-Notes-Tree.pdf
AD3251-Data Structures Design-Notes-Tree.pdf
 
Farhana shaikh webinar_treesindiscretestructure
Farhana shaikh webinar_treesindiscretestructureFarhana shaikh webinar_treesindiscretestructure
Farhana shaikh webinar_treesindiscretestructure
 
Lecture 5 tree.pptx
Lecture 5 tree.pptxLecture 5 tree.pptx
Lecture 5 tree.pptx
 
Data structures
Data structuresData structures
Data structures
 
Unit 3 Tree chapter 5
Unit 3  Tree chapter 5Unit 3  Tree chapter 5
Unit 3 Tree chapter 5
 

Dernier

Servosystem Theory / Cybernetic Theory by Petrovic
Servosystem Theory / Cybernetic Theory by PetrovicServosystem Theory / Cybernetic Theory by Petrovic
Servosystem Theory / Cybernetic Theory by PetrovicAditi Jain
 
CHROMATOGRAPHY PALLAVI RAWAT.pptx
CHROMATOGRAPHY  PALLAVI RAWAT.pptxCHROMATOGRAPHY  PALLAVI RAWAT.pptx
CHROMATOGRAPHY PALLAVI RAWAT.pptxpallavirawat456
 
OECD bibliometric indicators: Selected highlights, April 2024
OECD bibliometric indicators: Selected highlights, April 2024OECD bibliometric indicators: Selected highlights, April 2024
OECD bibliometric indicators: Selected highlights, April 2024innovationoecd
 
User Guide: Capricorn FLX™ Weather Station
User Guide: Capricorn FLX™ Weather StationUser Guide: Capricorn FLX™ Weather Station
User Guide: Capricorn FLX™ Weather StationColumbia Weather Systems
 
Citronella presentation SlideShare mani upadhyay
Citronella presentation SlideShare mani upadhyayCitronella presentation SlideShare mani upadhyay
Citronella presentation SlideShare mani upadhyayupadhyaymani499
 
STOPPED FLOW METHOD & APPLICATION MURUGAVENI B.pptx
STOPPED FLOW METHOD & APPLICATION MURUGAVENI B.pptxSTOPPED FLOW METHOD & APPLICATION MURUGAVENI B.pptx
STOPPED FLOW METHOD & APPLICATION MURUGAVENI B.pptxMurugaveni B
 
ECG Graph Monitoring with AD8232 ECG Sensor & Arduino.pptx
ECG Graph Monitoring with AD8232 ECG Sensor & Arduino.pptxECG Graph Monitoring with AD8232 ECG Sensor & Arduino.pptx
ECG Graph Monitoring with AD8232 ECG Sensor & Arduino.pptxmaryFF1
 
Vision and reflection on Mining Software Repositories research in 2024
Vision and reflection on Mining Software Repositories research in 2024Vision and reflection on Mining Software Repositories research in 2024
Vision and reflection on Mining Software Repositories research in 2024AyushiRastogi48
 
Pests of castor_Binomics_Identification_Dr.UPR.pdf
Pests of castor_Binomics_Identification_Dr.UPR.pdfPests of castor_Binomics_Identification_Dr.UPR.pdf
Pests of castor_Binomics_Identification_Dr.UPR.pdfPirithiRaju
 
Fertilization: Sperm and the egg—collectively called the gametes—fuse togethe...
Fertilization: Sperm and the egg—collectively called the gametes—fuse togethe...Fertilization: Sperm and the egg—collectively called the gametes—fuse togethe...
Fertilization: Sperm and the egg—collectively called the gametes—fuse togethe...D. B. S. College Kanpur
 
GENERAL PHYSICS 2 REFRACTION OF LIGHT SENIOR HIGH SCHOOL GENPHYS2.pptx
GENERAL PHYSICS 2 REFRACTION OF LIGHT SENIOR HIGH SCHOOL GENPHYS2.pptxGENERAL PHYSICS 2 REFRACTION OF LIGHT SENIOR HIGH SCHOOL GENPHYS2.pptx
GENERAL PHYSICS 2 REFRACTION OF LIGHT SENIOR HIGH SCHOOL GENPHYS2.pptxRitchAndruAgustin
 
Pests of jatropha_Bionomics_identification_Dr.UPR.pdf
Pests of jatropha_Bionomics_identification_Dr.UPR.pdfPests of jatropha_Bionomics_identification_Dr.UPR.pdf
Pests of jatropha_Bionomics_identification_Dr.UPR.pdfPirithiRaju
 
Microphone- characteristics,carbon microphone, dynamic microphone.pptx
Microphone- characteristics,carbon microphone, dynamic microphone.pptxMicrophone- characteristics,carbon microphone, dynamic microphone.pptx
Microphone- characteristics,carbon microphone, dynamic microphone.pptxpriyankatabhane
 
Pests of soyabean_Binomics_IdentificationDr.UPR.pdf
Pests of soyabean_Binomics_IdentificationDr.UPR.pdfPests of soyabean_Binomics_IdentificationDr.UPR.pdf
Pests of soyabean_Binomics_IdentificationDr.UPR.pdfPirithiRaju
 
Base editing, prime editing, Cas13 & RNA editing and organelle base editing
Base editing, prime editing, Cas13 & RNA editing and organelle base editingBase editing, prime editing, Cas13 & RNA editing and organelle base editing
Base editing, prime editing, Cas13 & RNA editing and organelle base editingNetHelix
 
GenBio2 - Lesson 1 - Introduction to Genetics.pptx
GenBio2 - Lesson 1 - Introduction to Genetics.pptxGenBio2 - Lesson 1 - Introduction to Genetics.pptx
GenBio2 - Lesson 1 - Introduction to Genetics.pptxBerniceCayabyab1
 
ALL ABOUT MIXTURES IN GRADE 7 CLASS PPTX
ALL ABOUT MIXTURES IN GRADE 7 CLASS PPTXALL ABOUT MIXTURES IN GRADE 7 CLASS PPTX
ALL ABOUT MIXTURES IN GRADE 7 CLASS PPTXDole Philippines School
 
《Queensland毕业文凭-昆士兰大学毕业证成绩单》
《Queensland毕业文凭-昆士兰大学毕业证成绩单》《Queensland毕业文凭-昆士兰大学毕业证成绩单》
《Queensland毕业文凭-昆士兰大学毕业证成绩单》rnrncn29
 
Pests of Bengal gram_Identification_Dr.UPR.pdf
Pests of Bengal gram_Identification_Dr.UPR.pdfPests of Bengal gram_Identification_Dr.UPR.pdf
Pests of Bengal gram_Identification_Dr.UPR.pdfPirithiRaju
 

Dernier (20)

Servosystem Theory / Cybernetic Theory by Petrovic
Servosystem Theory / Cybernetic Theory by PetrovicServosystem Theory / Cybernetic Theory by Petrovic
Servosystem Theory / Cybernetic Theory by Petrovic
 
CHROMATOGRAPHY PALLAVI RAWAT.pptx
CHROMATOGRAPHY  PALLAVI RAWAT.pptxCHROMATOGRAPHY  PALLAVI RAWAT.pptx
CHROMATOGRAPHY PALLAVI RAWAT.pptx
 
OECD bibliometric indicators: Selected highlights, April 2024
OECD bibliometric indicators: Selected highlights, April 2024OECD bibliometric indicators: Selected highlights, April 2024
OECD bibliometric indicators: Selected highlights, April 2024
 
Volatile Oils Pharmacognosy And Phytochemistry -I
Volatile Oils Pharmacognosy And Phytochemistry -IVolatile Oils Pharmacognosy And Phytochemistry -I
Volatile Oils Pharmacognosy And Phytochemistry -I
 
User Guide: Capricorn FLX™ Weather Station
User Guide: Capricorn FLX™ Weather StationUser Guide: Capricorn FLX™ Weather Station
User Guide: Capricorn FLX™ Weather Station
 
Citronella presentation SlideShare mani upadhyay
Citronella presentation SlideShare mani upadhyayCitronella presentation SlideShare mani upadhyay
Citronella presentation SlideShare mani upadhyay
 
STOPPED FLOW METHOD & APPLICATION MURUGAVENI B.pptx
STOPPED FLOW METHOD & APPLICATION MURUGAVENI B.pptxSTOPPED FLOW METHOD & APPLICATION MURUGAVENI B.pptx
STOPPED FLOW METHOD & APPLICATION MURUGAVENI B.pptx
 
ECG Graph Monitoring with AD8232 ECG Sensor & Arduino.pptx
ECG Graph Monitoring with AD8232 ECG Sensor & Arduino.pptxECG Graph Monitoring with AD8232 ECG Sensor & Arduino.pptx
ECG Graph Monitoring with AD8232 ECG Sensor & Arduino.pptx
 
Vision and reflection on Mining Software Repositories research in 2024
Vision and reflection on Mining Software Repositories research in 2024Vision and reflection on Mining Software Repositories research in 2024
Vision and reflection on Mining Software Repositories research in 2024
 
Pests of castor_Binomics_Identification_Dr.UPR.pdf
Pests of castor_Binomics_Identification_Dr.UPR.pdfPests of castor_Binomics_Identification_Dr.UPR.pdf
Pests of castor_Binomics_Identification_Dr.UPR.pdf
 
Fertilization: Sperm and the egg—collectively called the gametes—fuse togethe...
Fertilization: Sperm and the egg—collectively called the gametes—fuse togethe...Fertilization: Sperm and the egg—collectively called the gametes—fuse togethe...
Fertilization: Sperm and the egg—collectively called the gametes—fuse togethe...
 
GENERAL PHYSICS 2 REFRACTION OF LIGHT SENIOR HIGH SCHOOL GENPHYS2.pptx
GENERAL PHYSICS 2 REFRACTION OF LIGHT SENIOR HIGH SCHOOL GENPHYS2.pptxGENERAL PHYSICS 2 REFRACTION OF LIGHT SENIOR HIGH SCHOOL GENPHYS2.pptx
GENERAL PHYSICS 2 REFRACTION OF LIGHT SENIOR HIGH SCHOOL GENPHYS2.pptx
 
Pests of jatropha_Bionomics_identification_Dr.UPR.pdf
Pests of jatropha_Bionomics_identification_Dr.UPR.pdfPests of jatropha_Bionomics_identification_Dr.UPR.pdf
Pests of jatropha_Bionomics_identification_Dr.UPR.pdf
 
Microphone- characteristics,carbon microphone, dynamic microphone.pptx
Microphone- characteristics,carbon microphone, dynamic microphone.pptxMicrophone- characteristics,carbon microphone, dynamic microphone.pptx
Microphone- characteristics,carbon microphone, dynamic microphone.pptx
 
Pests of soyabean_Binomics_IdentificationDr.UPR.pdf
Pests of soyabean_Binomics_IdentificationDr.UPR.pdfPests of soyabean_Binomics_IdentificationDr.UPR.pdf
Pests of soyabean_Binomics_IdentificationDr.UPR.pdf
 
Base editing, prime editing, Cas13 & RNA editing and organelle base editing
Base editing, prime editing, Cas13 & RNA editing and organelle base editingBase editing, prime editing, Cas13 & RNA editing and organelle base editing
Base editing, prime editing, Cas13 & RNA editing and organelle base editing
 
GenBio2 - Lesson 1 - Introduction to Genetics.pptx
GenBio2 - Lesson 1 - Introduction to Genetics.pptxGenBio2 - Lesson 1 - Introduction to Genetics.pptx
GenBio2 - Lesson 1 - Introduction to Genetics.pptx
 
ALL ABOUT MIXTURES IN GRADE 7 CLASS PPTX
ALL ABOUT MIXTURES IN GRADE 7 CLASS PPTXALL ABOUT MIXTURES IN GRADE 7 CLASS PPTX
ALL ABOUT MIXTURES IN GRADE 7 CLASS PPTX
 
《Queensland毕业文凭-昆士兰大学毕业证成绩单》
《Queensland毕业文凭-昆士兰大学毕业证成绩单》《Queensland毕业文凭-昆士兰大学毕业证成绩单》
《Queensland毕业文凭-昆士兰大学毕业证成绩单》
 
Pests of Bengal gram_Identification_Dr.UPR.pdf
Pests of Bengal gram_Identification_Dr.UPR.pdfPests of Bengal gram_Identification_Dr.UPR.pdf
Pests of Bengal gram_Identification_Dr.UPR.pdf
 

Unit – vi tree

  • 1. Unit – VI Tree Prepared By: Dabbal Singh Mahara 1
  • 2. a. Concept and definition b. Binary tree c. Introduction and application d. Operations e. Types of binary tree  Complete binary tree  Strictly binary tree  Almost complete binary tree f. Tree traversal  Pre-order traversal  In-order traversal  Post-order traversal g. Binary search tree  searching  insertion  deletion h. Expression Tree i. Huffman algorithm j. AVL Trees Tree data structure 2By Dabal Mahara
  • 3. Introduction • A tree is an abstract model of a hierarchical structure that consists of nodes with a parent-child relationship. A tree is a finite set of data items or nodes such that:  There is a special data-item called the root of the tree  Its remaining data items are partitioned into mutually exclusive sub- sets, each of which itself is a tree, called sub-trees.
  • 4. Characteristics of trees:  Non-linear data structure  Combines advantages of an ordered array  Searching as fast as in ordered array  Insertion and deletion as fast as in linked list Application:  Directory structure of a file store  Structure of arithmetic expressions  Hierarchy of an organization Some key terms  Degree of a node: The degree of a node is the number of children of that node. In above tree , degree(A) = 2.  Degree of a Tree: The degree of a tree is the maximum degree of nodes in a given tree. In the above tree, maximum degree of nodes is 2, thus the degree of the tree is 2.  Path: It is the sequence of consecutive edges from source node to destination node. There is a single unique path from the root to any node. 4By Dabal Mahara
  • 5. Height of a node: The height of a node is the maximum path length from that node to a leaf node. A leaf node has a height of 0.  Height of a tree: The height of a tree is the height of the root.  Depth of a node: Depth of a node is the path length from the root to that node. The root node has a depth of 0.  Depth of a tree: Depth of a tree is the maximum level of any leaf in the tree. This is equal to the longest path from the root to any leaf. Level of a node: The level of a node is 0, if it is root; otherwise it is one more then its parent. 5By Dabal Mahara
  • 6. • A is the root node • B is the parent of E and F • D is the sibling of B and C • E and F are children of B • E, F, G, D are external nodes or leaves • A, B, C are internal nodes • Depth of F is 2 • the height of tree is 2 • the degree of node A is 3 • The degree of tree is 3 Illustration: 6By Dabal Mahara
  • 7. Binary Trees  A binary tree is a finite set of elements that are either empty or is partitioned into three disjoint subsets.  The first subset contains a single element called the root of the tree.  The other two subsets are themselves binary trees called the left and right sub-trees of the original tree. A left or right sub tree can be empty.  Each element of a binary tree is called a node of the tree. The following figure shows a binary tree with 9 nodes where A is the root. 7By Dabal Mahara
  • 8. Binary tree properties:  If a binary tree contains m nodes at level l , it contains at most 2m nodes at level l + 1.  Since a binary tree can contain at most 1 node at level 0 (the root), it contains at most 2l nodes at level l. Types of binary tree  Strictly binary tree  Almost complete binary tree  Complete binary tree 8By Dabal Mahara
  • 9.  If every non-leaf node in a binary tree has non-empty left and right sub-trees, then such a tree is called a strictly binary tree. Strictly binary tree  The following tree is not strictly binary tree, Since node E has a left son but not a right son. 9By Dabal Mahara
  • 10.  A strictly binary tree of depth d is called complete binary tree if all of whose leaves are at level d.  A complete binary tree with depth d has 2d leaves and 2d -1 non-leaf nodes (internal). Complete binary tree: Example: In this tree d = 3, therefore, leaves = 23 = 8 Internal nodes = 23 -1 = 7 10By Dabal Mahara
  • 11. A binary tree of depth d is an almost complete binary tree if: i. Any node at level less than d-1 has two sons. ii. For any node in the tree with a right descendant at level d, the node must have a left son and every left descendant of the node is either a leaf at level d or has two sons. Almost complete binary tree: 11By Dabal Mahara
  • 12. B J G F C I ED H A K Level 0 Level 1 Level 2 Level 3 This tree is not almost complete binary tree because it does not satisfy condition ii. That is, node A has right descendent at level 3 ( J or K), but it has left descendent leaf node at level 2 (node E). 12By Dabal Mahara
  • 13. Operations on Binary tree:  father(n,T): Return the parent node of the node n in tree T. If n is the root, NULL is returned.  LeftChild(n,T): Return the left child of node n in tree T. Return NULL if n does not have a left child.  RightChild(n,T): Return the right child of node n in tree T. Return NULL if n does not have a right child.  Info(n,T): Return information stored in node n of tree T (ie. Content of a node).  Sibling(n,T): return the sibling node of node n in tree T. Return NULL if n has no sibling.  Root(T): Return root node of a tree if and only if the tree is nonempty.  Size(T): Return the number of nodes in tree T  MakeEmpty(T): Create an empty tree T  SetLeft(S,T): Attach the tree S as the left sub-tree of tree T  SetRight(S,T): Attach the tree S as the right sub-tree of tree T.  Preorder(T): Traverses all the nodes of tree T in preorder.  postorder(T): Traverses all the nodes of tree T in postorder  Inorder(T): Traverses all the nodes of tree T in inorder. 13By Dabal Mahara
  • 14. • Array representation • Linked Representation Binary Tree Representation Array Representation An array is used to store the nodes of the binary tree. Nodes stored in the array are accessed sequentially, root is at index 0 and then left child and right child are stored. To store the elements of the binary tree of depth d, declare the array of size 2d+1 -1, i.e. the total number of nodes of complete binary tree and store the elements level wise. If root is at I then left child is t 2i+1 and right child is at 2i+2. B J G F C I ED H A0 1 2 4 7 5 14 6 3 10 Declare array of size 2 3+1 -1 = 15 Char a[15] A B C D E F G H I J 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 14By Dabal Mahara
  • 15. Linked Representation of Binary Tree • It is the most popular way to present a binary tree. Each element is represented by a node that has two link fields (leftChild and rightChild) plus an element field. Each binary tree node is represented as an object whose data type is binaryTreeNode . • The space required by an n node binary tree is: n * sizeof(binaryTreeNode) C representation for Binary tree struct binaryTreeNode { int info; struct binaryTreenode *left; struct binaryTreenode *right; }; struct binaryTreenode *root=NULL; 15By Dabal Mahara
  • 16. The given tree can be represented in linked list as given below. 16By Dabal Mahara
  • 17.  The tree traversal is a way in which each node in the tree is visited exactly once in a symmetric manner.  There are three popular methods of traversal i. Pre-order traversal ii. In-order traversal iii. Post-order traversal Tree traversal 17By Dabal Mahara
  • 18. 1. Pre-order traversal: The preorder traversal of a nonempty binary tree is defined as follows: i. Visit the root node ii. Traverse the left sub-tree in preorder iii. Traverse the right sub-tree in preorder The preorder traversal output of the given tree is: A B D H I E C F G The preorder is also known as depth first order. C function for preorder traversing: void preorder(struct bnode *root) { if(root!=NULL) { printf(“%c”, root->info); preorder(root->left); preorder(root->right); } } 18By Dabal Mahara
  • 19. The inorder traversal of a nonempty binary tree is defined as follows: i. Traverse the left sub-tree in inorder ii. Visit the root node iii. Traverse the right sub-tree in inorder The inorder traversal output of the given tree is: H D I B E A F C G C function for inorder traversing: void inorder(struct binaryTreenode *root) { if(root!=NULL) { inorder(root->left); printf(“%c”, root->info); inorder(root->right); } } 2. In-order traversal: 19By Dabal Mahara
  • 20. 3. Post-order traversal: The post-order traversal of a nonempty binary tree is defined as follows: i. Traverse the left sub-tree in post-order ii. Traverse the right sub-tree in post-order iii. Visit the root node C function for post-order traversing: void post-order(struct bnode *root) { if(root!=NULL) { post-order(root->left); post-order(root->right); printf(“%c”, root->info); } } The post-order traversal output of the given tree is: H I D E B F G C A 20By Dabal Mahara
  • 21. Q. Design a binary tree whose traversal sequences are given below: Pre-order: CPRBLOEMATIK In-Order: BRLPEOMCTAIK Solution: Since preorder traverses from root of the tree, C is root of the tree. The { B, R, L, P, E, O, M} and {T, I, A, K } are respectively left and right sub tree . (from inorder sequence) C T, A, I, K B, R, L, P, E, O, M 21By Dabal Mahara
  • 22. C I, KB, R, L, P E, O, M A T Similarly, for left sub tree { B, R, L, P, E, O, M}, root is P ( from preorder sequence) and {B, R, L} is left sub-tree and {E, O, M} is right sub-tree. ( From inorder sequence) For right sub-tree {T, A, I, K}, A is the root. ( from preorder sequence) T is left sub-tree and {I, K } is right sub-tree. 22By Dabal Mahara
  • 23. Similarly, R is root for sub-tree {B, R, L} ( from preorder sequence) B is left child and L right child of R ( from inorder sequence) O is root for sub-tree {E, O, M} (from preorder sequence) E is left child and M is right child of O (from inorder sequence) In the same way, I is root and K is right child for sub-tree { I, K } C P A TO I KL M R EB 23By Dabal Mahara
  • 24. Q. A binary tree T has 12 nodes. The in-order and post-order traversals of T yield the following sequence of nodes: In-order : VPNAQRSOKBTM Post-order : VANRQPBKOMTS Construct the Binary tree T showing each step. Explain how you can arrive at solution in brief. Solution: Since post-order traversal visits all nodes in left sub-tree , right sub-tree and root recursively, the last node in the sequence is root of the tree. That is, S is the root. In-order traversal visits the nodes in Left child, root and right child in recursive way, { V,P, N,A, Q, R} is left sub-tree and {O, K, B, T, M} is the right sub tree. S O, K, B, T, M V, P, N, A, Q, R Step -1: 24By Dabal Mahara
  • 25. S O, K, B P T MV N, A, Q, R O S K, B P N, A T MV Q R Step -2: The root of { V, P, N, A, Q, R} is P obtained from postorder sequence. Left subtree and right sub trees are {v} and {N, A, Q, R} obtained from inorder sequence. Similarly, for { O, K, T, B, M} , root is T and left sub tree {O, K, B} and right sub tree is {M}. Step -3: In the same way, root and sub trees are obtained. 25By Dabal Mahara
  • 26. S P T MV Q R Step -4: The final tree is given below. O K B A N Thus, root of the tree is obtained from post-order sequence scanning from right to left and left and right sub-trees of corresponding root are obtained from inorder sequence. 26By Dabal Mahara
  • 27. An important application of binary trees is their use in searching. A binary search tree (BST) is a binary tree that is either empty or in which every node contains a key (value) and satisfies the following conditions: i. All keys in the left sub-tree of the root are smaller than the key in the root node. ii. All keys in the right sub-tree of the root are greater than the key in the root node. iii. The left and right sub-trees of the root are again binary search trees . Binary search tree(BST) 27By Dabal Mahara
  • 28. Binary Search Trees 1 4 2 3 8 6 1 4 2 3 8 6 7 • The tree on the left is a binary search tree, but the tree on the right is not. 28By Dabal Mahara
  • 29. Given the following sequence of numbers, 14, 15, 4, 9, 7, 18, 3, 5, 16, 20, 17, 5 The following binary search tree can be constructed: 14 4 9 15 7 5 17 2016 3 18 The inorder traversal of BST gives the sorted sequence in ascending order. So, inorder traversal of above BST is: 3, 4, 5, 7, 9, 14, 15, 16, 17, 18, 20. 29By Dabal Mahara
  • 30. Following operations can be done in BST:  Search(k, T): Search for key k in the tree T. If k is found in some node of tree then return true otherwise return false.  Insert(k, T): Insert a new node with value k in the info field in the tree T such that the property of BST is maintained.  Delete(k, T):Delete a node with value k in the info field from the tree T such that the property of BST is maintained.  FindMin(T), FindMax(T): Find minimum and maximum element from the given nonempty BST. Operations on Binary search tree(BST): 30By Dabal Mahara
  • 31. struct bstnode { int info; //Declaring an info field struct bstnode *left; // left child pointer struct bstnode *right; // right child pointer }; Structure of BST node Struct bstnode *root = NULL; 31By Dabal Mahara
  • 32. To find if any node of a BST contains an element equal to target: 1. Set curr to the BST’s root. 2. Repeat: 2.1. If curr is null: 2.1.1. Terminate with answer none. 2.2. Otherwise, if target is equal to curr’s element: 2.2.1. Terminate with answer curr. 2.3. Otherwise, if target is less than curr’s element: 2.3.1. Set curr to curr’s left child. 2.4. Otherwise, if target is greater than curr’s element: 2.4.1. Set curr to curr’s right child. 2. end BST search algorithm : 32By Dabal Mahara
  • 33. C function for BST searching: void BinSearch(struct bstnode *root , int key) { if(root == NULL) { printf(“The number does not exist”); } else if (key == root->info) { printf(“The searched item is found”): } else if(key < root->info) BinSearch(root->left, key); else BinSearch(root->right, key); } 33By Dabal Mahara
  • 34. To insert a new item in a tree, we must first verify that its key is different from those of existing elements. To do this a search is carried out. If the search is unsuccessful, then item is inserted. Idea: To insert a new element into a BST, proceed as if searching for that element. If the element is not already present, the search will lead to a null link. Replace that null link by a link to a leaf node containing the new element. Insertion of a node in BST: 15 9 13 12 10 18 20 22 25 Insertion of element 13 34By Dabal Mahara
  • 35. To insert the element elem into a BST: 1. Set parent to null, and set curr to the BST’s root. 2. Repeat: 2.1. If curr is null: 2.1.1. Replace the null link from which curr was taken (either the BST’s root or parent’s left child or parent’s right child) link to a newly-created leaf node with element elem. 2.1.2. Terminate. 2.2. Otherwise, if elem is equal to curr’s element: 2.2.1. Terminate. 2.3. Otherwise, if elem is less than curr’s element: 2.3.1. Set parent to curr, and set curr to curr’s left child. 2.4. Otherwise, if elem is greater than curr’s element: 2.4.1. Set parent to curr, and set curr to curr’s right child. 3.End BST insertion algorithm : 35By Dabal Mahara
  • 36. C function for BST insertion: Struct bstnode * insert(struct bstnode *root, int item) { if(root=NULL) { root=(struct bstnode*)malloc (sizeof(struct bnode)); root->left=root->right=NULL; root->info=item; } else if ( item == root->info) { printf("n Duplicate not allowed."); return root; } else { if(item<root->info) root->left=insert(root->left, item); else root->right=insert(root->right, item); } } 36By Dabal Mahara
  • 37. While deleting a node from BST, there may be three cases: 1. The node to be deleted may be a leaf node: In this case simply delete a node and set null pointer to its parents those side at which this deleted node exist. Deleting a node from the BST: 37By Dabal Mahara
  • 38. 2. The node to be deleted has one child: In this case the child of the node to be deleted is appended to its parent node. Suppose node to be deleted is 18 Delete(18) 38By Dabal Mahara
  • 39. 3. The node to be deleted has two children: In this case node to be deleted is replaced by its in-order successor node. That is, the node to be deleted is either replaced by its right sub-trees leftmost node or its left sub-trees rightmost node. Suppose node to deleted is 12. Find minimum element in the right sub-tree of the node to be removed. In current example it is 19. Delete(12) 39By Dabal Mahara
  • 40. General algorithm to delete a node from a BST: 1. start 2. if a node to be deleted is a leaf node at left side then simply delete and set null pointer to it's parent's left pointer. 3. If a node to be deleted is a leaf node at right side then simply delete and set null pointer to it's parent's right pointer. 4. if a node to be deleted has one child then connect it's child pointer with it's parent pointer and delete it from the tree. 5. if a node to be deleted has two children then replace the node being deleted either by a. right most node of it's left sub-tree or b. left most node of it's right sub-tree. 6. End 40By Dabal Mahara
  • 41. The delnode function: struct bstnode *delnode(struct bstnode *root, int item) { struct bstnode *temp; if(root==NULL) { printf(“Empty tree”); return; } else if(item<root->info) root->left=delnode(root->left, item); else if(item>root->info) root->right=delnode(root->right, item); else if(root->left!=NULL && root->right!=NULL) //node has two children { temp=findmin(root->right); root->info=temp->info; root->right=delnode(root->right, root->info); } else { temp=root; if(root->left==NULL) root=root->right; else if(root->right==NULL) root=root->left; free(temp); } return(root); } 41By Dabal Mahara
  • 42. struct bstnode * findmin(struct bstnode * root) { if(root==NULL) return NULL; else if(root->left ==NULL) return head; else return(findmin(root->left)); } 42By Dabal Mahara
  • 43. Expression Tree An expression tree is a strictly binary tree in which leaf node contains operands and non-leaf node contain operators. Root nodes contain the operators that is applied to the result of left and right sub trees. The operators, constants, and variables are arranged in such a way that an inorder traversal of the tree produces the original expression without parentheses. Example: 1 An expression tree of an expression (a + b *c ) +((c*e +f) *g) *a + * g+ f * ec c + b Exercise: Construct an expression tree of an expression: (a + b ) /((c-d) *e) 43By Dabal Mahara
  • 44. Expression Tree Examples Inorder Traversal ResultExpression TreeExpression a + 3(a+3) 3+4*5-9+63+(4*5-(9+6)) log xlog(x) n !n! + 3a + -3 * 54 + 69 log x ! n 44By Dabal Mahara
  • 45. Constructing an Expression Tree From Postfix Expression Algorithm • We read the expression one symbol at a time. • If the symbol is an operand, we create a one-node tree and push a pointer to it onto a stack. • If the symbol is an operator, we pop pointers to two trees T1 and T2 from the stack (T1 is popped first) and form a new tree whose root is the operator and whose left and right children point to T2 and T1, respectively. A pointer to this new tree is then pushed onto the stack. 45By Dabal Mahara
  • 46. Example: • Input: 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. a b  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. a b +  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. a b + c d e 46By Dabal Mahara
  • 47. Constructing an Expression Tree a b + c • Now a ‘+’ is read, so two trees are merged. d e + a b + c  Continuing, a ‘*’ is read, so we pop two tree pointers and form a new tree with a ‘*’ as root. d e + * 47By Dabal Mahara
  • 48. Constructing an Expression Tree a b + c  Finally, the last symbol is read, two trees are merged, and a pointer to the final tree is left on the stack. d e + * * Exercise: Construct an expression from postfix expression: AB+C*DC--FG+$ 48By Dabal Mahara
  • 49. • Proposed by Dr. David A. Huffman at MIT in 1952 – “A Method for the Construction of Minimum Redundancy Codes” • Huffman coding is a form of statistical coding – more frequently used symbols have shorter code words – Not all characters occur with the same frequency! – Yet all characters are allocated the same amount of space – 1 char = 1 byte, be it e or x • Huffman coding is a technique used to compress files for transmission • Works well for text and fax transmissions The Huffman Coding 49By Dabal Mahara
  • 50. Huffman Algorithm 1. Initially, each symbol is one node tree by itself. That is, there is forest of n nodes each labelled with symbol and weight. 2. Repeat while n>1 i. Select the two trees T1 and T2 with minimum weights from the forest. ii. Merge T1 and T2 to form T3 with weight sum of both trees. iii. Insert T3 into the forest. 3. Assign 0 to each left path of tree and 1 to right path. The code for each symbol is obtained by collecting bits on the paths from root to the leaf node labelled with the symbol. • Huffman codes is text compression method, which relies on the relative frequency (i.e., the number of occurrences of a symbol) with which different symbols appear in a text • Uses extended binary trees • Variable-length codes that satisfy the property, where no code is a prefix of another • Huffman tree is a binary tree with minimum weighted external path length for a given set of frequencies (weights). Huffman Code 50By Dabal Mahara
  • 51. Example: 1 Let us take any four characters and their frequencies as follows: Char frequency E 10 T 7 O 5 A 3 • Without using Huffman coding, these four characters can be represented by using two bits as: 00 -> E, T ->01, O ->10 and A-> 11. This is fixed length coding. So, bits required to encode all the characters in the above message will be: ( 10 +7+5+3) * 2 = 50 bits • Huffman coding technique uses variable length code depending upon the frequency of characters used in the text. It's coding technique is as follows: First sort the characters by their frequency in non-decreasing order. Char frequency A 3 O 5 T 7 E 10 51By Dabal Mahara
  • 52. 1. Create a forest of one node trees for each character as: A : 3 O : 5 T : 7 E: 10 2. Merge two minimum trees as a single tree and add it to the forest in the order. T1 : 8 O: 5A : 3 T : 7 E: 10 3. Repeat step 2 again. T2 : 15 T : 7 T1 : 8 O: 5A : 3 E: 10 52By Dabal Mahara
  • 53. 4. Repeat the step 2 again. T3: 25 E: 10 T2 : 15 T : 7 T1 : 8 O: 5A : 3 T3: 25 E: 10 T2 : 15 T : 7 T1 : 8 O: 5A : 3 5. Assign 0 to left path and 1 to right path in the tree. 0 0 0 1 1 1 This tree is called Huffman tree. 53By Dabal Mahara
  • 54. Now the code for each characters are as obtained by collecting the bits from root to the character node. The codes are: Char code frequency E 0 10 T 10 7 A 110 3 O 111 5 Therefore, total number of bits required = 10* 1 +7 *2 + 3 *3 + 5 *3 =48 bits The space saved = (50-48)/50 *100 % = 4 % 54By Dabal Mahara
  • 55. Example: 2 Let us take any four characters and their frequencies as follows: Char frequency a 10 e 15 i 12 s 3 t 4 Sp (space) 13 nl (new line) 1 Fixed Length Format: These 7 characters can be represented by three bits. So, total number of bits = (10+15+12+3+4+13+1) * 3 = 174 Using Huffman Coding First sort the characters by their frequency in non-decreasing order. Char frequency nl (new line) 1 s 3 t 4 a 10 i 12 Sp (space) 13 e 15 55By Dabal Mahara
  • 56. 1. Create a forest of one node trees for each character as: 2. Merge two minimum trees as a single tree and add it to the forest in the order. T1 : 4 S : 3 nl : 1 3. Repeat step 2 again. nl : 1 s: 3 t : 4 a: 10 i: 12 sp: 13 e: 15 t : 4 a: 10 i: 12 sp: 13 e: 15 a: 10 i: 12 sp: 13 e: 15 T2 : 8 T1 : 4 S : 3 nl : 1 t : 4 56By Dabal Mahara
  • 57. 4. Repeat step 2 again. i: 12 sp: 13 e: 15 T2 : 8 T1 : 4 S : 3nl : 1 t : 4 T3 : 18 a : 10 5. Repeat step 2 again. e: 15 T4: 25 sp: 13i: 12 T2 : 8 T1 : 4 S : 3nl : 1 t : 4 T3 : 18 a : 10 57By Dabal Mahara
  • 58. 6. Repeat step 2 again. sp: 13 T4: 25 i: 12 T2 : 8 T1 : 4 S : 3nl : 1 t : 4 T3 : 18 a : 10 e: 15 T5: 33 58By Dabal Mahara
  • 59. sp: 13 T4: 25 i: 12 T2 : 8 T1 : 4 S : 3nl : 1 t : 4 T3 : 18 a : 10 e: 15 T5: 33 T6: 58 7. Repeat step 2 again. 59By Dabal Mahara
  • 60. sp: 13 T4: 25 i: 12 T2 : 8 T1 : 4 S : 3nl : 1 t : 4 T3 : 18 a : 10 e: 15 T5: 33 T6: 58 8. Assign 0 to left path and 1 to right path in the tree. 0 1 0 0 0 0 0 1 1 1 1 1 This tree is called Huffman tree. 60By Dabal Mahara
  • 61. Now the code for each characters are as obtained by collecting the bits from root to the character node. The codes are: Char code frequency i 00 12 sp 01 13 e 10 15 nl 11000 1 S 11001 3 t 1101 4 a 111 10 Therefore, total number of bits required = 12*2 +13 *2 + 15 *2 + 1 *5 +3 * 5 + 4*4 + 10 * 3 = 146 bits The space saved = (174-146)/174 *100 % = 16.09 % 61By Dabal Mahara
  • 62. AVL (Adelson-Velskii and Landis) Trees • An AVL Tree is a binary search tree such that for every internal node v of T, the heights of the children of v can differ by at most 1. 88 44 17 78 32 50 48 62 2 4 1 1 2 3 1 1 An example of an AVL tree where the heights are shown next to the nodes: 62By Dabal Mahara
  • 63. 5 3 8 1 4 10 AVL Tree 5 3 1 4 Not AVL Tree • All operations depend on the depth of the tree. • BSTs are limited because of their bad worst-case performance O(n). • AVL trees are height-balanced binary search trees • An AVL tree has balance factor calculated at every node For every node, heights of left and right subtree can differ by no more than 1 • It allows dynamic insert and remove with O(log(N)) time complexity. • Balanced search trees are trees whose heights in the worst case is O(lg n) 63By Dabal Mahara