Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 60

UNIT-4

Trees
Definition of Trees
Terminology
Binary Tree
Types of Binary Tree
Binary Search Tree
Representation of a Binary Tree
 Binary Search Tree operations
Insertion, Deletion, Searching
Tree Traversals
AVL Tree
AVL Tree operations
Insertion, Deletion, Searching
2
Tree
 Tree is a non-linear data structure.
 A tree, is a finite set of nodes together with a finite set of directed
edges(links/branches) that define parent-child
(Hierarchical )relationships.
 Example:
Nodes = {A,B,C,D,E,F,G,H}
Edges = {(A,B),(A,E),(B,F),(B,G),(B,H),(E,C),(E,D)}

 A tree is a finite set of one or more nodes such that:


 There is a specially designated node called the root.

 Remaining nodes are partitioned into ‘n’ (n>0) disjoint sets


T1,T2,..Tn, where each Ti (i=1,2,….n) is a Tree, T1,T2,..Tn are
called sub tree of the root.
A
E B
D C F H G
3
A tree satisfies the following properties:

1. It has one designated node, called the root, that has no parent.
2. Every node, except the root, has exactly one parent.
3. A node may have zero or more children.
4. There is a unique directed path from the root to each node.

5 5
5
1
3 2 3 2
3 2

4 1 6 4 6
4 1 6
tree Not a tree Not a tree

4
Tree Terminology
Root: Only node with no parent Example: A
Parent of x: The node directly above node x in the tree (A, B, C, H)
Child of x: A node directly below node x in the tree (B,C,D,E,F,G,H,I)
Siblings: Nodes with common parent. (B,C),(D,E),(F,G,H)
Non-leaf or Internal Node: Nonleaf node. (B,C,H)
Path: A sequence of connected nodes. (A,B,D), (A,C,H,I), ...
Ancestor of x: A node on the path from the root to x. For D (A,B)
Descendent of x: A node on a path from x to a leaf.
For C (H,I)
Leaf or External Node: A node with no children. (D,E,F,G,I)

B C

D E F G H

I
5
The level of a node x: It is the distance from the root to node x.
Generally, the root has a zero distance from itself, the root is at level 0.
The, children of the root are at level 1, their children are at level at 2,
and so on. Level of j: 3

Height of Tree: The maximum no of nodes covered in a path


starting from root node to a leaf node is called height of a tree.
Height of a following tree: 5

Depth: Length of the path to that node from the root. 3 for
G
Degree/arity of node x: Number of children's of a node x. Degree of c: 3
A Level 0

B C Level 1
D E F G Level 2
H I J Level 3
k Level 4
6
Example 2:

7
TERM DESCRIPTION EXAMPLE
Node An item or single element represented in a A,B,C…….,H
tree
Root Node that does not have any ancestors A
(parent
or Grandparent)
Sub tree Internal nodes in a tree which has both B,C,D
ancestor(parent) and descendant(child)
Leaf External nodes that does not have any E,F,G,H
descendant(child)
Edge The line depicts the connectivity between (A-B),(A-C)…
two
nodes
Path Sequence of nodes connected A-B-E for E from root
Height Length of the longest path from the root 3
Depth Length of the path to that node from the 2 for D
root
Degree of a Number of children connected from that 3 for A, 1 for B,D, 2 for C
node node and 0 for leaves
8
Degree of a Degree of a node which has maximum 3 (since A has Max.
Binary Tree
 In a binary tree, each node has at most two sub trees.
 A binary tree(T) is a finite set of nodes such that:
 T is empty tree (called empty binary tree)
 T contains a specially designed node called the root of T, and
remaining nodes of T form two disjoint binary trees T1 and T2
which are called left sub tree and right sub tree respectively.

Note: A binary tree is a tree in which no nodes can have more than two
children.

9
Binary Tree Properties

1. A binary tree with n elements, n > 0, has exactly n-1 edges.


2. A binary tree of height h, h >= 0, has at least h and at most 2h-1
elements or nodes in it.
3. The height of a binary tree that contains n elements, n >= 0, is at
least (log2(n+1)) and at most n.

Minimum and Maximum number of elements for height 4

minimum number of elements maximum number of elements


10
Difference between tree and binary tree

Trees

1) Tree never be empty.


2) A node may have any no of
nodes/children’s.

Binary tree

1) Binary tree may be empty.


2) A node may have at most 2 children's or 0 or1
children.

11
Full binary tree
A full binary tree is a tree in which every node other than the leaves has
two children.
Note: All leaves are at same level and all other nodes each have two children.
A full binary tree of height h has exactly 2h-1 nodes.

1 Level 0- 1node

2 3 Level 1- 2nodes

5 6 7 Level 2- 4nodes
4

10 12 13 14 15 Level 3-8nodes
8 9 11

12
Complete binary tree
A complete binary tree is a binary tree in which every level is completely
filled except possibly the last level.
In the unfilled level, the nodes are attached starting from the left-most position.

1 Level 0- 1node

2 3 Level 1- 2 nodes

4 5 6 7 Level 2- 4 nodes

8 9 Level 3- 2 nodes
13
Balanced Binary Tree
Balanced binary tree is a binary tree in which the left and right sub
trees
height must be differed by at most 1.

2 Left sub tree height = 3


3
Right sub tree height = 2

4 5 6 7

Difference = 1
8 9

14
 Left skewed binary tree
If the right subtree is missing in every node of tree then we
call it as left skewed tree.
A
B
C
 Right skewed binary tree
If the left subtree is missing in every node of a tree then we
call it is right subtree. A
B
C

15
Binary Search Tree
A binary search tree is a nonempty binary tree that satisfies the following
properties:
 Each node has a key/element (or value), and no two nodes have the
same key (i.e., all keys are distinct).
 For every node x, all keys/elements in the left sub tree of x are
smaller than x.
 For every node x, all keys in the right sub tree of x are larger than or
equal to x.
 The left and right sub trees of the root are also binary search trees.

Fig (a) is not a BST where as Fig (b) and (c) are BST’s

16
Binary Search Tree Operations
1. Searching:
 Search begins at the root.
 If the root is NULL, the search tree is empty and the search fails.
 If key is less than the root, then left subtree is searched.
 If key is greater than the root, then right subtree is searched.
 If key equals the root, then the search terminates successfully.

20
Search for 8

10 40

6 15 30

2 8 25
17
Binary Search Tree Operations
2.Insertion:

 To insert a new element into a binary search tree, we must first


verify that its key does not already exist by performing a search
in the tree.
 If the search is successful, we do not insert.
 If the search is unsuccessful, then the element is inserted at the
point the search terminated.

Insert 35
20

10 40

6 15 30

2 8 25 35
18
Binary Search Tree Operations
3.Deletion:
There are three cases for the element to be deleted:
1.Element is in a leaf.
2.Element is in a degree 1 node (i.e., has exactly one nonempty
subtree).
3.Element is in a degree 2 node (i.e., has exactly two nonempty
subtrees).
Case 1: Delete from a Leaf.
For case 1, we can simply discard the leaf node.
Example, delete a leaf element. Key = 7.

20

10 40

6 15 30

2 8 18 25 35
7
19
Case 2: Delete from a Degree 1
Node 20

Delete 40 10 40

6 15 30

2 8 18 25

20
Delete 15
10

6 15 30

2 8 18 25
20
Case 3: Delete from a Degree 2
Node 20
10 40
6 15 30
2 8 18 25 35
7
Replace with the largest key in the left subtree (or the smallest in the
right subtree)
20

8 40

6 15 30

2 8 18 25 35

21
7
Representation of a Binary Tree using Array

Sequential Representation :
 Tree nodes are stored in a linear data structure like array.
 Root node is stored at index ‘0’
 If a node is at a location ‘i’, then its left child is located at 2 * i + 1
and right child is located at 2 * i + 2

The space required by a binary tree of height h is 2h-1.

22
Example: Sequential representation
0
A

1 2
B D

3
5 G 6
C E

F 12

A B D C . E G . . . . . F

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
23
Advantages of array/sequential/static representation
 Any node can be accessed from any other node by calculating the
index and this is efficient from execution point of view.

 There is no overhead of maintaining the pointers.

Disadvantages of Static Representation


 The major disadvantage with this type of representation is wastage of
memory. Example: In the skewed tree, half of the array is
unutilized.

 Allows only static representation. There is no possible way to enhance


the size of the tree.

 Inserting a new node and deleting a node from it are inefficient with
this representation because these require considerable data movement
up and down the array which demand excessive processing time.

24
Representation of Binary Tree using Linked List

 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 .

 The space required by an n node binary tree is n * sizeof a node.

struct node { /* a node in the tree structure */


struct node *lchild;
int data ;
struct node *rchild;
};
The pointer lchild stores the address of left child node.
The pointer rchild stores the address of right child node.
If child is not available NULL is stored.
A pointer variable root represents the root of the tree.
25
Linked Representation of Binary Tree

2626
Advantages of linked representation
 This representation is superior to the array representation as there is
no wastage of memory.

 There is no need to have prior knowledge of depth of the tree. Using


dynamic memory allocation concept one can create as much memory
(node) as required.

 Insertion and deletion which are the most common operations can be
done without moving the other nodes.

Disadvantages of linked representation

 This representation does not provide direct access to a node.

 It needs additional space in each node for storing the left and right
subtrees.
27
Binary Tree Traversal Techniques

 There are three recursive techniques for binary tree


traversal.
1. Preorder Traversal
2. Inorder Traversal
3. Postorder Traversal

28
Algorithm preOrder (root)
Traverse a binary tree in root-left-right
Pre Condition: root is the entry node of a tree or
subtree
Post Condition: each node has been processed in order
1. if(root is not null)
1. process(root)
2. preOrder(leftsubtree)
3. preOrder(rightsubtree)
2. end if
end preOrder

29
Algorithm inOrder (root)
Traverse a binary tree in left-root-right
Pre Condition: root is the entry node of a tree or
subtree
Post Condition: each node has been processed in order
1. if(root is not null)
1. inOrder(leftsubtree)
2. process(root)
3. inOrder(rightsubtree)
2. end if
end inOrder

30
Algorithm postOrder (root)
Traverse a binary tree in left-right-root
Pre Condition: root is the entry node of a tree or
subtree
Post Condition: each node has been processed in order
1. if(root is not null)
1. postOrder(leftsubtree)
2. postOrder(rightsubtree)
3. process(root)
2. end if
end postOrder

31
Preorder of binary tree

B C

D E F G

H J
I

Preorder: A B D E H I C F J K G
32
Inorder of binary tree

B C

D E F G

H J
I

Inorder: D B H E I A F K J C G

33
Postorder of binary tree

B C

D E F G

H J
I

K
Postorder: D H I E B K J F G C A

34
Write pre,in and post order of the following tree:

(A-B) + C* (D/E) +

- *

A B C /

D E

35
Preorder for the following tree

- *

A B C /

D E
Preorder: + - A B * C / D E

36
Inorder of the following tree

- *

A B C /

D E
Inorder: A - B + C * D / E

37
Postorder of the following tree

- *

A B C /

D E

Postorder: A B - C D E / * +

38
/* Write a C program that uses functions to perform the following:
i) Creating a Binary Tree of integers.
ii) Traversing the above binary tree in preorder, inorder and postorder.*/

bnode* getnode(int ele)


{
bnode *q = (bnode*)malloc(sizeof(bnode));
#include <stdio.h> if(q)
#include <conio.h> {
struct node q -> data = ele;
{ q -> lchild = NULL;
int data; q -> rchild = NULL;
struct node *lchild,*rchild; return q;
}; }
typedef struct node bnode; else
{
printf("\n Unable to create the node");
exit(0);
}
return 0;
39
}
void preorder(bnode *root)
{
if(root!=NULL)
{
printf("%5d",root->data); void postorder(bnode *root)
preorder(root->lchild); {
preorder(root->rchild); if(root!=NULL)
} {
} postorder(root->lchild);
postorder(root->rchild);
void inorder(bnode *root) printf("%5d",root->data);
{ }
if (root!=NULL) }
{
inorder(root->lchild);
printf("%5d",root->data);
inorder(root->rchild);
}
}
40
bnode* insert(bnode *root, int ele)
{
if(root==NULL)
{
bnode *q = getnode(ele);
root = q;
}
else if(root->data < ele)
root->rchild = insert(root->rchild, ele);
else if(root -> data > ele)
root -> lchild = insert(root -> lchild, ele);
else
{
printf("\n Duplicate data ");
}
return root;
}

41
void main() {
int ch, ele;
bnode *root = NULL;
printf("\n Binary Search Tree Operations :");
printf("\n\t 1) Insert \n\t 2) Preorder \n\t 3) Inorder\n\t4 ) Postorder \n\t 5)
Exit"); while(1) {
printf("\n Enter your choice :");
scanf("%d", &ch);
switch(ch) {
case 1: printf("\n Enter an element :");
scanf("%d", &ele);
root = insert(root, ele); break;
case 2: preorder(root); break;
case 3: inorder(root); break;
case 4: postorder(root); break;
case 5: exit(0);
default : printf("\n Invalid choice.");
}//switch
}
}//main
42
Applications of Trees

Trees are very important data structures in computing.


They are suitable for:
– Hierarchical structure representation, e.g.,
• File directory.
• Organizational structure of an institution.
• Class inheritance tree.
– Problem representation, e.g.,
• Expression tree.
• Decision tree.
– Efficient algorithmic solutions, e.g.,
• Search trees.
• Efficient priority queues via heaps.

43
AVL TREES
• A binary search tree is said to be height balanced binary
search tree.
• If all its nodes have a balance factor of -1,0,1.
- That is |bf|=|hL-hR|, for every node in the tree.

• Andelson,Velski and Lendis introduced binary tree structure


that is balanced with respect to height of subtree.
Steps to convert unbalanced to balanced :

1.Insert node into a binary search tree.

2.Compute the balance factors

3.Decide the pivot node

4.Balance the unbalanced tree.


AVL rotations
• Single rotation
- left to left
- right to right
• Double rotations
- left to right
- right to left
• Case 1:LEFT LEFT(LL)
- unbalance occurred due to the insertion in
the left sub tree of the left child of the pivot
node.

P A

P
A
PR AL

AL AR AR PR
• Insert 2

8
8

6 10
6 10

4
7 9 11
4 7 9 11

3 5
3 5

2
8

4 10

3 6 9 11

2 5 7
• Case 2:RIGHT RIGHT(rr)
- unbalance occurred due to the insertion in
the RIGHT sub tree of the RIGHT child of the
pivot node.

P B

B
P
PL BR

BL BR PL BL
• Inserting 12
7
7

5 9
5 9

4 6 8 11
4 6 8 11

10 13
10 13

12
Case 3:LEFT SUB TREE OF RIGHT CHILD(LR)
Unbalanced occurred due to the insertion in the left sub tree of the
right child of the pivot node.

P
P

A
PR B
PR
B A
AL BR

BL BR AL BL
B

A P

AL BL BR PR
Case 4:RIGHT SUB TREE OF LEFT CHILD(RL)
Unbalanced occurred due to the insertion in the right sub tree of the
left child of the pivot node.

P P

A B
PL

B AR A
PL BL

BL BR BR AL
B

P A

PL BL BR AR
AVL Tree operations (Insertion and Deletion Example)
15, 20, 24, 10, 13, 7, 30, 36, 25
20
Pivot
15
15 24

20 A
10
24 B
13

20 20
Pivot
13 24 15 24

10 15 13 A

10 B
15, 20, 24, 10, 13, 7, 30, 36, 25

Pivot 20
13

A 13 24 10 20

B 10 15 7 15 24 Pivot

7 30 A

13 36 B

10 20

7 15 30

24 36
15, 20, 24, 10, 13, 7, 30, 36, 25

13 13

10 20 Pivot 10 20

7 15 A 30 7 15 24

B 24 36 30

25 13 25 36

10 24

7 20 30

15 25 36
Delete 24 and 20 from the AVL tree.

13 13

10 24 10 20

7 20 30 7 15 30

15 25 36 25 36

13 13

10 30 10 15

7 15 36 7 30

25 25 36
Applications of Trees

Trees are very important data structures in computing.


They are suitable for:
– Hierarchical structure representation, e.g.,
• File directory.
• Organizational structure of an institution.
• Class inheritance tree.
– Problem representation, e.g.,
• Expression tree.
• Decision tree.
– Efficient algorithmic solutions, e.g.,
• Search trees.
• Efficient priority queues via heaps.

60

You might also like