You are on page 1of 59

What is a Tree

• A tree is a finite nonempty


set of elements.
• A tree is a collection of N
nodes, one of which is the
root and N-1 edges.
• It is an abstract model of a
hierarchical structure.
• consists of nodes with a
parent-child relation.
• Applications:
– Organization charts
– File systems
– Programming environments
Tree Terminology
• Root: unique node in the tree to which further subtrees are
attached
• Parent node: the node having further sub-branches
• Siblings: nodes with same parent
• Internal node: node with at least one child
• External node (leaf ): node without children
• Height of a tree: maximum depth of any node
• Degree of the node: the total number of sub-trees attached to
that node
• Degree of a tree: the maximum degree in the tree.
• Subtree is a subset of a tree is itself a tree.
• Level : each node in a tree assigned a level number. Root is 0
• Depth or height of a tree is the maximum level of the tree.
Binary trees
 Definition – is a finite set of nodes which is either empty or consists of a
root and two disjoint binary trees called the left and right sub-trees.
Each node of can have at most two children.
 Full binary tree – is a tree in which every node has zero or two children
 Complete binary tree – is a full binary tree in which all the leaves at
the same depth
• The total number of nodes in complete binary tree are 2 (h+1) – 1
• The number of leaf nodes n in a complete binary tree can be n= 2h
 Left skewed tree – each node is attached as a left child of parent node
 Right skewed tree - each node is attached as a right child of parent
node
 Ordered binary tree- the left child node will always be less than its
parent & right child node will greater than its parent.
 Unordered binary tree – does not follow any such ordering.

3
Operations on Binary Tree
 Traversals
 refers to visiting all the nodes of a BT exactly once in a
systematic way.
 Preorder
 In-order
 Post-order
 Insertion
 To insert a new element into the tree
 Deletion
 To remove an element from the tree
 Searching
 Checks whether the given data is present in the tree or not
Representation of Binary Tree
 Array or sequential representation
– Key concept is that, if s parent is stored in location k,
then its left and right child are located in locations 2k
and 2k+1 respectively.
 Advantages
– Direct access to any node can be possible and finding
the parent, left or right children of any particular node is
fast.
 Disadvantages
– Wastage of memory
– Insertion and deletion of any node in the tree will be
costlier
Contd..
 Linked representation
– Each node will have left , right and data field.
 Advantages
– Superior to array representation as there is no wastage
of memory
– Insertion and deletions can be done without moving the
other nodes.
 Disadvantages
– Does not provide direct access to a node & special
algorithms are required.
– Needs additional space in each node for storing the left
and right sub-trees.
FA Questions
1. A binary tree whose every node has either zero
or two children is called
a. Full binary tree b. Binary search tree
c. Extended binary tree d. B-tree
Ans:a
2. A terminal node in a binary tree is called ______
b. Root b. Leaf c. Child d. Branch
Ans:b
Applications
Expression trees
Binary search trees
Threaded binary trees
FA Questions
1. The operation of processing each element in
the list is known as ______
a. Inserting b. Sorting c. Merging d. Traversal
Ans:d
A Binary Expression Tree is . . .
A binary tree may be used to represent and evaluate
an arithmetic expression.
A special kind of binary tree in which:
1. Each leaf node contains a single operand
2. Each nonleaf node contains a single binary operator
Expression Tree

‘*’

‘-’ ‘/’

‘8’ ‘5’ ‘+’ ‘3’

‘4’ ‘2’
A Binary Expression Tree

‘*’

‘+’ ‘3’

‘4’ ‘2’

What value does it have?

( 4 + 2 ) * 3 = 18
Easy to generate the infix, prefix, postfix expressions (how?)

‘*’

‘-’ ‘/’

‘8’ ‘5’ ‘+’ ‘3’

‘4’ ‘2’

Infix: ((8-5)*((4+2)/3))
Prefix: *-85 /+423
Postfix: 85- 42+3/*
Constructing an expression tree
• Strongly resembles the postfix evaluation.
• Read the expression one symbol at a time.
• If the symbol is an operand, create a one node tree
and push a pointer to it onto a stack.
• If the symbol is an operator, pop pointers to two
trees T1 and T2 from the stack and form a new tree
whose root is the operator and whose L & R
children point to T2 & T1.
• A pointer to this new tree is then pushed onto the
stack.
• Example: a b + c d e + * *
Exercise
Construct the expression tree from the following
postfix expression
1. a b c - d * +
2. 8 5 – 4 2 + 3 / *
3. D E + F G - *
4. 1 5 + 8 10 + *
5. A B C * +
6. A b c - + d e - f g + h - / *
FA Questions
1. The postfix expression for the infix expression (A * B - (C - D)) /
(E + F) is
a. A B * C D - - E F + / b. A B * C D- EF-+/ c. A*BCD- -EF+/ d.
A*BCD-EF+ - /
Ans : A
2. The leaf nodes of binary expression tree contains
a. Both operators and operands b. only operators c. only
operands d. neither b or c
Ans : c
3. The root node of the expression tree of (a/b*c)+(5-4+(d+e)*f) is
a. + b. * c. - d. /
Ans: A
Binary Search Trees- Introduction
 The binary search tree the data is systematically arranged.
 Values at left sub-tree<root node value< right sub-tree value
 Property
 The value of root node N is greater than every value in the left sub-tree
of N and is less than every value in the right sub-tree of N.
 Operations
 makeEmpty – used for initialization
 Find – returning pointer to the node in tree T ie key X or NULL.
 Findmin and findmax
 Insertion
 Deletion

17
Binary Search Tree- Operations
 makeEmpty – is mainly used for initialization
makeEmpty(Searchtree T)
{
if(T!=NULL)
{
makeEmpty(T -> left);
makeEmpty(T-> right);
}
return NULL;
}

18
Binary Search Tree- Operations
 Find
Find( Elementtype X, SearchTree T)
{
if( T==NULL)
return NULL;
if(X< T-> element)
return Find( X, T->left);
else
if(X>T->element)
return Find(X, T->right);
else
return T;
}
19
Binary Search Tree- Operations
 Findmax – return the position of the largest element in the
tree
Findmax (SearchTree T)
{
if( T!=NULL)
while(T-> right! = NULL)
T=T-> right;
return T;
}

20
Binary Search Tree- Operations
Insertion if (X<T->element)
Insert(element type X, searchtree T)
{ T->left = insert(X,T->left);
if (T==NULL) else
{
T=malloc(sizeof(struct TreeNode));
if (X>T->element)
if (T==NULL) T->right=insert(X,T->right);
fatalerror (“Out of space”);
else
else
{ X is in the tree already
T->element =X; return T
T->left=T->right=NULL;
} }
}

21
Binary Search Tree- Operations
 Deletion – 3 cases
 deletion of leaf node
 Deletion of node having one child
 Deletion of node having 2 children
 Deletion of leaf node
if (temp ->left ==NULL) && (temp->right== NULL)
{
if (parent->left == temp)
parent ->left=NULL;
else
parent ->right=NULL;
}

22
Binary Search Tree- Operations
 Deletion of a node having one child(ie left child)
if (temp ->left!=NULL) && (temp->right== NULL)
{
if (parent->left == temp)
parent ->left= temp->left;
else
parent ->right = temp->left;
temp=NULL;
free (temp);
}

23
Binary Search Tree- Operations
 Deletion of a node having one child(ie right child)
if (temp ->left==NULL) && (temp->right!= NULL)
{
if (parent->left == temp)
parent ->left= temp->right;
else
parent ->right = temp->right;
temp=NULL;
free (temp);
}

24
Binary Search Tree- Operations
 Deletion of a node having two children
if (temp ->left!=NULL) && (temp->right!= NULL)
{
parent = temp;
temp_succ=temp->right;
while(temp_succ->left!=NULL)
{
parent=temp_succ;
temp_succ=temp_succ ->left;
}
temp->data=temp_succ->data;
parent->data=NULL;
return;
}
25
FA Questions
1.Which traversal technique traverses the elements of
binary search tree in ascending order.
a.pre-order b. post-order c. in-order d. converse post-order
Ans:c
2. Create a binary search tree using the following
operations: insert 3, insert 7, insert 8, insert 1, insert 5,
insert 0, insert 4, insert 6, insert 9.  Then, the left and
right child of the in-order successor of node 5 is
a.0 and 6 b. 4 and null c. 3 and 9 d. 4 and 6
Ans: d
AVL Trees- Introduction
 Self balancing BST
 An AVL(Adelson Velskii and Landis) tree is a BST
with a balance condition.
 AVL Tree is a height balanced binary search tree in
which the height of left subtree and height of right
subtree can differ at most by 1.
 The T is height balanced if and only if ,
– TL and TR are height balanced
– hL – hR <= 1, hL & hR are heights of TL and TR
 Balance factor (BF)
 The BF of a node in BT is defined to be hL – hR ,
 The factors are -1,0 or +1
• 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
– Store current heights in each node
• A node N with BalanceFactor(N) < 0 is called "left-
heavy", one with BalanceFactor(N) > 0 is called
"right-heavy", and one with BalanceFactor(N) = 0 is
sometimes simply called "balanced".
AVL Trees- Representation
 An AVL tree follows the property of BST with a
balance factor as -1,0,or +1.
 The BF is denoted at right top corner inside the
node.
 After insertion of any node in AVL tree violating
the property, restore the destroyed balance
condition.
AVL Trees- Insertion
 4 different cases
 An insertion of new node into left sub-tree of left child
(LL)
 An insertion of new node into right sub-tree of left
child (RL)
 An insertion of new node into left sub-tree of right
child (LR)
 An insertion of new node into right sub-tree of right
child (RR)
Some modifications done on AVL tree in order to
rebalance it is called rotations of AVL tree.
Insertion algorithm
 Insert a new node as new leaf just as in ordinary
BST.
 Now trace the path from insertion point towards
root. For each node ‘n’ encountered, check it
heights of left(n) and right(n) differ by at most 1.
a. if yes, move towards parent(n).
b. otherwise reconstruct by doing either a single

or a double rotation.
Insertion algorithm
 2 types of rotations
 Single rotation
 LL
 RR
 Double rotation
 LR
 RL
Right Rotation - Pseudo code
void right_rotation(struct node *p)
{
if (p->left != NULL)
{
struct node *x;
x = p->left; // store the left child pivot in x
p->left = x->right; // attach x->right child to pivots's left
if (x->right!=NULL) x->right->parent = p; // update parent ptr of x
x->right = p; // attach pivot to right of x
if (p->parent != NULL)
if(p == p->parent->right) p->parent->right=x;
else
p->parent->left = x;
x->parent = p->parent;
p->parent = x;
if (p == root) //update root if required
root = x;
}
}
Left Rotation
void left_rotation(struct node *p)
{
if (p->right != NULL)
{
struct node *x;
x = p->right; //store the right of pivot in x
p->right = x->left; //attach x left to pivot's right
if (x->left!=NULL) x->left->parent = p; // update x's left parent ptr
x->left = p; // attach pivot to left of x
if (p->parent != NULL)
if (p==p->parent->left) p->parent->left=x;
else
p->parent->right=x;
x->parent = p->parent;
p->parent = x;
if(p == root)
root=x;
}
}
FA Questions
1. Insert the following elements into an empty
binary search tree with balance indicators:
5,4,3,2,1. Then the balance factor of root node is
a. +4 b. -4 c. +3 d. -3
Ans:a
2. The maximum balance factor a node can arrive
at during insertion operation into an avl tree is
a. +2 or -2 b. -1 or +1 c. +1 only d. -1 only
Ans: b
• Traversing the tree means visiting each node
exactly once.
• Six ways to traverse a tree
• Here L- Left, R-Right & N-Root nodes
• In this LNR, LRN, NLR,NRL,RLN, RNL. But
computing point of view we have first 3 different
ways of traversing a tree.
• These three combinations are called inorder,
preorder & postorder.
Recursive inorder traversal
• If tree is not empty then
traverse the left sub-tree in inorder
visit the root node
traverse the right sub-tree in inorder
Void inorder(node *temp)
{
if (temp!=NULL)
{
inorder(temp ->left);
printf(%d”,temp->data);
inorder(temp ->right);

}
}
Recursive preorder traversal
• If tree is not empty then
visit the root node
traverse the left sub-tree in preorder
traverse the right sub-tree in preorder
void preorder(node *temp)
{
if (temp!=NULL)
{
printf(%d”,temp->data);
preorder(temp ->left);
preorder(temp ->right);

}
}
Recursive postorder traversal
• If tree is not empty then
traverse the left sub-tree in postorder
traverse the right sub-tree in postorder
visit the root node
void postorder(node *temp)
{
if (temp!=NULL)
{
postorder(temp ->left);
postorder(temp ->right);
printf(%d”,temp->data);
}
}
B - TREES
Introduction
• B-trees are balanced search trees
• Designed to work well on Direct Access
secondary storage devices (magnetic disks).
• B-trees are widely used in database systems
Motivation

• When data is too large to fit in main memory, then


the number of disk accesses becomes important.
• A disk access is unbelievably expensive compared
to a typical computer instruction (mechanical
limitations).
• One disk access is worth about 200,000
instructions.
• The number of disk accesses will dominate the
running time.

42
Motivation Cont..
• Secondary memory (disk) is divided into
equal-sized blocks (typical sizes are 512,
2048, 4096 or 8192 bytes)
• The basic I/O operation transfers the contents
of one disk block to/from main memory.
• Our goal is to devise a multiway search tree
that will minimize file accesses (by exploiting
disk block read).

43
Definition of a B-tree
• A B-tree of order m is an m-way tree (i.e., a tree where each
node may have up to m children) in which:
1. the number of keys in each non-leaf node is one less than
the number of its children and these keys partition the keys
in the children in the fashion of a search tree
2. all leaves are on the same level
3. all non-leaf nodes except the root have at least m / 2
children
4. the root is either a leaf node, or it has from two to m
children
5. a leaf node contains no more than m – 1 keys
• The number m should always be odd
STRUCTURAL PROPERTIES OF B-TREES

A B-tree of order m is a tree with the following


structural properties:
• The root is either a leaf or has between 2 and
m children.
• All non leaf nodes (except the root) have
between ceil(m/2) and m children.
• All leaves are at the same depth.
• A B-tree is a method of placing and locating
files (called records or keys) in a database. The
B-tree algorithm minimizes the number of
times a medium must be accessed to locate a
desired record, thereby speeding up the
process.
Properties of B-Tree

• A B-Tree T is a rooted tree having the following properties:


1. Every node x has the following fields:
1. n[x] the no. of keys currently stored in node x
2. The n[x] keys themselves, stored in non-decreasing order, so
that key1[x] ≤ key2[x]…… ≤keyn-1[x] ≤ keyn[x].
3. Leaf[x], a Boolean value that is TRUE if x is a leaf and FALSE if
x is an internal node.
2. Each internal node x also contains n[x]+1 pointers
(Childs) c1[x], c2[x],---------cn[x]+1[x].
3. All leaves have the same depth, which is the tree’s
height h.
Constructing a B-tree
• Suppose we start with an empty B-tree and
keys arrive in the following order:1 12 8 2 25
6 14 28 17 7 52 16 48 68 3 26 29 53 55
45
• We want to construct a B-tree of order 5
• The first four items go into the root:
1 2 8 12

• To put the fifth item in the root would violate


condition 5
• Therefore, when 25 arrives, pick the middle
key to make a new root
1
1
2
Constructing a B-tree
8
2
2 Add 6 to the tree
5
6
1
4
2 Exceeds Order.
8 Promote middle and
1 split.
7
7
1 2 8 12 25
5
2
1
6
4
8
6
8
1
1
2
Constructing a B-tree (contd.)
8
2
2 8
5
6
1
4
2 1 2 12 25
8
1 6, 14, 28 get added to the leaf nodes:
7
7 8
5
2
1
6
4 1 2 1 6 2 12 14
25 28
8
6
8
1
1
2
Constructing a B-tree (contd.)
8
2
2 Adding 17 to the right leaf node would over-fill it, so we take
5
6 the middle key, promote it (to the root) and split the leaf
1
4 8
2
8
1
7
7 1 2 6
2 25 28 28
12 14 17
5
2
1
6
4
8
6
8
1
1
2
Constructing a B-tree (contd.)
8
2
2
7, 52, 16, 48 get added to the leaf nodes
5
6
1
4 8 17
2
8
1
7
7 1 2 76 12 14
16 25 28 52
48
5
2
1
6
4
8
6
8
1
1
2
Constructing a B-tree (contd.)
8
2
2 Adding 68 causes us to split the right most leaf,
5
6 promoting 48 to the root
1
4
2
8
1 8 17
7
7
5
2 1 2 6 7 12 14 16 25 28 48 52 68
1
6
4
8
6
8
1
1
2
Constructing a B-tree (contd.)
8
2
2 Adding 3 causes us to split the left most leaf
5
6
1 8 17 48
4
2
8
1
7 1 2
3 6 7 12 14 16 25 28 52 68
7
5
2
1
6
4
8
6
8
1
1
2
Constructing a B-tree (contd.)
8
2
2 Add 26, 29, 53, 55 then go into the leaves
5
6
1 3 8 17 48
4
2
8
1
7 1 2 6 7 12 14 16 25262829 52536855
7
5
2
1
6
4
8
6
8
1
1
2
Constructing a B-tree (contd.)
8
2 Exceeds Order.
2 Add 45 increases the trees level Promote middle and
5
split.
6
1
4
2 Exceeds Order.
8 Promote middle and
1
3 8 17 48 split.
7
7
5
2 1 2 6 7 12 14 16 25 26 28 29 45 52 53 55 68
1
6
4
8
6
8
Constructing a B-tree (contd.)

17

3 8 28 48

1 2 6 7 12 14 16 25 26 29 45 52 53 55 68

B-Trees 57
Inserting into a B-Tree
• Attempt to insert the new key into a leaf
• If this would result in that leaf becoming too big, split the
leaf into two, promoting the middle key to the leaf’s
parent
• If this would result in the parent becoming too big, split
the parent into two, promoting the middle key
• This strategy might have to be repeated all the way to the
top
• If necessary, the root is split in two and the middle key is
promoted to a new root, making the tree one level higher

B-Trees 58
Exercise in Inserting a B-Tree
• Insert the following keys to a 5-order B-tree:

3, 7, 9, 23, 45, 1, 5, 14, 25, 24, 13, 11, 8, 19, 4,


31, 35, 56

B-Trees 59

You might also like